# How to best maintain a sorted list from a stream of integers?

If I have an incoming stream of integers how can I best maintain a sorted list of them? The only way I can think of is to binary search for the position and shifting the remaining elements to the right. This would amount to $$O(N + \log N)$$ time. Is there a better data structure that can help me achieve the same in better time? I know we can use a Balanced Binary Search Tree with $$O(\log N)$$ insertions but I would like to have efficient access on the list.

• B-tree......... – Bulat Mar 11 '19 at 14:19
• Does it allow random access? – Andrew Scott Mar 11 '19 at 14:24
• Possible duplicate of Adding elements to a sorted array – xskxzr Mar 11 '19 at 17:43
• @AndrewScott I would like to advise you to avoid using random access to mean efficient access. You can just say "efficient access" or "fast access". Here is the conventional meaning of random access in computer science. – John L. Mar 11 '19 at 17:57
• Important edit - maintaining sorted list will be O(N^2). Any sort of balanced tree will be O(N*logN) – Bulat Mar 11 '19 at 20:06

A balanced binary search tree can support access to arbitrary elements in $$O(\log N)$$ time per access. Augment the data structure to store, in each node, the number of values stored in the subtree under that node. Then you can find the $$i$$th largest value in the list in $$O(\log N)$$ time as well; thus, all basic operations can be done in $$O(\log N)$$ time.
• @D.W. thank you. That is indeed an efficient solution. As far as the random access is concerned, I meant I only want to pick the $i$th element fairly efficiently. – Andrew Scott Mar 11 '19 at 17:37