0

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

Jonathan
  • 55
  • 8

1 Answers1

-2

I will give the problem a shot.

let array = {1, 2, 3, 3, 3, 4, 5, 5, 6, 7, 10}

let k = 3

I assume you want findAll(k) to return {3, 3, 3} in this particular example. To do this, get, rid of the outer loop and do the following after the loop:

  1. Check item to the left of the found value. If that value is the same as the found value, repeat this step with that value. Else, stop.
  2. Do the same with checking to the right of the value found in the first loop.

After doing the above step, you should have two indices. Find the delta between the indices and add 1. Make a new array of that size and fill it with k.

pfnuesel
  • 14,093
  • 14
  • 58
  • 71
ljeabmreosn
  • 169
  • 8