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;
}
}
}
}