3

I implemented an nth_number selection algorithm using Medians of Medians. On wikipedia, it states that it's space complexity is O(1)

I had to store the medians in a temporary array in order to find the median amongst those medians. How would you be able to do it without using any extra memory? If it does not count as increasing its space complexity, please explain.

function nth_number(v, n) {
    var start = 0;
    var end = v.length - 1;
    var targetIndex = n - 1;

    while(true) {

        var medians = []; /* Extra memory. */

        /* Divide our array into groups of 5s. Find a median within each */
        for(var i = start; i <= end; i += 6) {
            if(i + 5 < end)
                medians.push(findMedian(v, i, i + 5));
            else 
                medians.push(findMedian(v, i, end));
        }

        var median = findMedian(medians, 0, medians.length - 1); /* Find the median of all medians */

        var index = partition(v, median, start, end);

        if(index === targetIndex) {
            console.log(median);
            return median;
        }
        else {
            if(index < targetIndex) {
                start = index + 1;
                targetIndex -= index;
            }
            else {
                end = index - 1;
            }
        }
    }
}
OmG
  • 15,398
  • 7
  • 42
  • 71
Kamran224
  • 1,384
  • 7
  • 19
  • 31

1 Answers1

3

The selection algorithm needs to rearrange the input vector, since it does a series of partitions. So it's reasonable to assume that it is possible to rearrange the input vector in order to find the median.

One simple possible strategy is to interleave the groups of five, instead of making them consecutive. So, if the vector has N == 5K elements, the groups of five are:

(0,   k,    2k,   3k,   4k)
(1,   k+1,  2k+1, 3k+1, 4k+1)
(2,   k+2,  2k+2, 3k+2, 4k+2)
...
(k-1, 2k-1, 3k-1, 4k-1, 5k-1)

Then when you find the median of a group of five, you swap it with the first element in the group, which means that the vector of medians will end up being the first k elements of the rearranged vector.

rici
  • 201,785
  • 23
  • 193
  • 283