Insert a number into a sorted array!

I would like to write a piece of code to insert a number into a sorted array at the appropriate position (i.e. the array will still remain sorted after insertion)

My data structure does not allow duplication.

I plan to do something like this:

  • Find the desired index where I should put this element using binary search
  • Create space for this item by moving all items from this index down.
  • Put this item there.

Is there any other better way?

+3
source share
3 answers

, , . , AA - . , , , , , blit .

+6

, - log n / .

+1

Should the data be sorted all the time? If this is not the case, if only fast access to the smallest or highest element is required, the Binary Heap gives constant access time and adding and removing login time. Moreover, it can satisfy your condition that the memory must be sequential, since you can implement BinaryHeap on top of the array (Ie; array [2n + 1] left child, array [2n + 2] right child).

+1
source

Source: https://habr.com/ru/post/1748833/


All Articles