When designing a dynamic array which will shrink, what is a method to keep track of the highest used index, and when that index’s held object is deleted, find the new highest used index.
Right now I can think up having a a simple int last_used and then charging the cost of maintaining this variable to the func_delete which must check if it deletes the highest, and if so, check each smaller value looking for a non null. (array will always be null initialized)
if(last_index == deleted_index){
while(last_index >0 && array[--last_index] != NULL)
// if the array is now only half full, I realloc
}
Is there any other smart ways?
It looks okay to me, but logic wise, if the function
func_deletealways deletes the highest item, then there shouldn’t be anyNULLvalues at smaller indices. So this should do:Edit:
based on your comments, I understand what you’re trying to do, I think you could just keep track of the highest used index in the insertion function instead:
And when you delete you check if the index is the highest or not. like you’re doing, don’t think there’s a better way to do that, without complicating things further, for example, you could keep another sorted list of indices, this way you when you delete the highest index you find the next one in constant time, but like I said, it complicates things. However, I think another data structure might be more useful, a linked list for example, is more efficient when randomly deleting nodes, but not when randomly inserting nodes.