I have a function as follows, intended to calculate the median using recursion (without any built in functions):
function [ val ] = findMedian( inputArray )
n=length(inputArray);
mid=ceil(n/2);
k=randi(1,n);
val=findTerm(inputArray,k);
function [ val ] = findTerm( inputArray,k )
inputArray=inputArray(:);
k=k-1;
while (1)
x=randi(length(inputArray));
val=x;
a1=inputArray<val;
n1=sum(a1);
if inputArray<n1
inputArray=inputArray(a1);
elseif k<(n1+sum(inputArray==val))
break;
else
inputArray=inputArray(inputArray>val);
k=k+numel(inputArray)-numel(a1);
end
end
end
end
However, when I sample this function using the command:
findMedian([1 2 3 4 5 6 7])
it produces 1 instead of the actual median 4. How do I change the while-loop to recursion?