Function Name: recurMedian Inputs (1): - (double) A 1xN array ofscalars Outputs
ID: 3617339 • Letter: F
Question
Function Name: recurMedian Inputs (1): - (double) A 1xN array ofscalars Outputs (1): - (double) The median of the inputarrayFunction Description: Given a 1xN array of scalars (a vector), write a functionrecurMedian that recursively calculates the median of the input array. Fora sorted array with an odd number of elements, the medianis defined as the middle element of the array. For a sorted arraywith an even number of elements, the median is defined as the average ofthe two middle elements of the array. Your function shouldreturn this median. Return an empty vector if the input is empty.
Constraints: You MUST use recursion to solve this problem.
Hints: As the input vector is not sorted, you should write a helperfunction that sorts it before you attempt to recursivelyfind the median. Your helper function should also catch the case wherethe input is empty. that way, you don't have to worry about thesecases when you are coding your recursive function.
Test Cases: a = recurMedian([-3 2 5 18 24 25 73]); a => 18 b = recurMedian([-10 4 23 25 48 52]); b => 24
c = recurMedian([]); c => [];
Function Name: recurMedian Inputs (1): - (double) A 1xN array ofscalars Outputs (1): - (double) The median of the inputarray
Function Description: Given a 1xN array of scalars (a vector), write a functionrecurMedian that recursively calculates the median of the input array. Fora sorted array with an odd number of elements, the medianis defined as the middle element of the array. For a sorted arraywith an even number of elements, the median is defined as the average ofthe two middle elements of the array. Your function shouldreturn this median. Return an empty vector if the input is empty.
Constraints: You MUST use recursion to solve this problem.
Hints: As the input vector is not sorted, you should write a helperfunction that sorts it before you attempt to recursivelyfind the median. Your helper function should also catch the case wherethe input is empty. that way, you don't have to worry about thesecases when you are coding your recursive function.
Test Cases: a = recurMedian([-3 2 5 18 24 25 73]); a => 18 b = recurMedian([-10 4 23 25 48 52]); b => 24
c = recurMedian([]); c => [];
Explanation / Answer
assuming you have an already sorted set, the code below will work.Otherwise, use the code I wrote for you from your other question tosort it. ------------------------------------------------------------------------------ function A=recurMedian(B) [m n]=size(B);%You can do error checking for m!=1 if (n==0) %empty A=ones(0,0); elseif (n==1) A=B; elseif (n==2) A=(B(1,1)+B(1,2))/2; else%n>2 B=B(1,2:end-1); A=recurMedian(B); end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.