This is from an assignment. The exact question is:
"Design a variation of binary search algorithm for performing the operation findAll(k) in a search table (i.e., a map which is implemented using a sorted array and which allows multiple entries with the same key) such that the new algorithm runs in O(log n + s) time, where n is the number of elements in the map and s is the size of the collection returned. You must provide the pseudo-code and explain how it achieves the required time complexity."
First thing I noticed is that I can't use recursion, since I'm using the same parameter k (key) to search through the entire table. So, this is what I have so far:
Algorithm findAll(k)
{
for i = 0 to end of array
{
mid = (low + high) / 2;
while k is not equal to mid
{
if k is less than mid
mid = (low + mid) / 2;
else
mid = (mid + high) / 2;
}
store k in collection array;
increment i;
}
return collection;
}
I want it to take O(log n) time for the search, and s time for storing all the matching keys in a separate array, which is returned at the end. The problem with this, is:
1) I have a loop within a loop, which is not what I want (the for loop was to determine the end).
2) While it will go through the entire array, it's going to search for the same key over and over again, and I can't remove it after every search because this is not a remove method.
How exactly can I improve my pseudocode?
Thanks