This is not clear from the question, but maybe this is what you want:
You can do something similar to find the index in the array where bsearch () matches.
if (bsearch_returned_address != NULL) index = (bsearch_returned_address - array_base_address)
EDIT
To find out the location the last bsort visitor visited, check out the material below.
Itβs good that the manual says:
It is assumed that the comparison procedure has two arguments that point to the key object and to the array element in this order and should return an integer less than, equal to or greater than zero if the key object is found, respectively, less to match or be more than an array element.
Therefore, you can save the second argument inside the comparison function in a global variable, and in case of failure, use the address in this variable, which indicates the last location that the bsearch function visited to find for matching.
For instance:
List with address and value:
[0x8d6010: 0][0x8d6014: 4][0x8d6018: 8][0x8d601c: 12][0x8d6020: 16][0x8d6024: 20][0x8d6028: 24][0x8d602c: 28][0x8d6030: 32][0x8d6034: 36]
Search Value
13
Exit
fmem: (nil) //this is the memory location where it was found last_mem1: 0x7fff8c8e6c54 //last val of 1st param of compare last_mem2: 0x8d601c //last val of 2nd param of compare *last_mem1: 13, *last_mem2: 12
Sample Comparison Function Code
static const int *last_mem1, *last_mem2; static int compmi(const void *a, const void *b) { last_mem1 = a; last_mem2 = b; return *(int *)a - *(int *)b; }
That way you can insert after the address in last_mem2 . Although there are terminal cases, if you find a key that is smaller than the first element, then last_mem2 will also have the address of the first element.
But no matter how you transfer the elements of the array to do this, to make the complexity of inserting O(n) . You can improve performance by introducing some kind of lazy insert, for example, make a separate unordered list, which is much smaller than your original list, and discard new items there. When searching, do bsearch in the source list and linear search in the dump. When the dump list exceeds a certain threshold, you can combine the list by sorting the insert. But still you cannot be O(lg n) .