I would like to write a piece of code for inserting a number into a sorted array at the appropriate position (i.e. the array should still remain sorted after insertion)
My data structure doesn’t allow duplicates.
I am planning to do something like this:
- Find the right index where I should be putting this element using binary search
- Create space for this element, by moving all the elements from that index down.
- Put this element there.
Is there any other better way?
If you really have an array and not a better data structure, that’s optimal. If you’re flexible on the implementation, take a look at AA Trees – They’re rather fast and easy to implement. Obviously, takes more space than array, and it’s not worth it if the number of elements is not big enough to notice the slowness of the blit as compared to pointer magic.