1

In c++, std::set which stores its element in sorted order can insert elements in O(log n) time. But all the methods i know take linear time:

Inserting the element at the end of the array and swapping it with the previous element until the previous element is less than it- takes linear time.

Using binary search on the array and finding the position the position of the element to be inserted: takes O(log n) time but inserting the element to the given position takes O(n) time in the worst case.

If we use the sorted array as heaps, we can insert an element in O(log n) time but even if the array remains a heap after that, there is no guarantee that it remains sorted.

I need a method to insert an element in a sorted array in O(log n) time, and i know this is possible because std::set can do it, but i dont know how.

j0k
  • 22,600
  • 28
  • 79
  • 90
2147483647
  • 1,177
  • 3
  • 13
  • 33
  • Have you taken a look at the source for std::set? – Will A Dec 04 '12 at 13:21
  • std::set is always sorted internally, and the only correct way to insert elements is to use the insert function. See [link](http://www.cplusplus.com/reference/set/set/) – TinyPinkSaxophone Dec 04 '12 at 13:22
  • @lindell std::set is available only in c++, not in c, i am looking for an algorithm which i can use, no matter what the programming language is – 2147483647 Dec 04 '12 at 13:36

1 Answers1

2

The solution is to use a different data-structure. std::set has for instance been implemented using a red-black-tree.

In general, you cannot do this with plain arrays.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283