using bsearch() in C (standard library) one can quickly find an entry in a sorted array.
However, how do I calculate where to insert a new entry (using the standard library)?
bsearch() specifically checks whether the found item’s key is equal to the passed key and if it isn’t, it returns NULL – so can’t use that.
Its not clear from the question but possibly this is what you want:
You can do something like this to find the index in the array where
bsearch ()found the match.EDIT
To know the location which the bsort last visited, check the below stuff out.
The good thing is that the manual says:
Therefore you can store the second argument inside the comparison function in a global variable, and in a case of the fail use the address in this variable, which points to the last location the
bsearchfunction visited to find for a match.For example:
A list with address and value:
Value to search
output
The sample compare function code is
So you can insert after the address in
last_mem2. Although there are terminal cases, if you find a key which is less than the first element, thenlast_mem2will also have the address of the first element.But how ever you have to shift the array elements to make place for the insertion, which will make the insertion complexity to
O(n). You might want to improve performance by introducing some kind of lazy insertion, like make a separate unordered list, which is much smaller than your original list, and dump new elements there. When searching, performbsearchin original list, and linear search in the dump. When the dump list grows past a certain threshold, you can merge the list by performing an insertion sort. But still, you can’t beO(lg n).