Help on the following question? Code Review Section Your co-worker has developed a function to find the median value in an unsorted array with an odd number of elements. For arrays with an even number of elements, this function does not apply. To normally find such a value would be to sort the array and then obtain the value at the middle index of the array. For example, [5 2 53 1 4], the median is 4 because when it is sorted, the array will be [1 2 4 5 53] and the value at the middle index is 4. Your co-worker’s function uses the partition function that is the same function as the one the QuickSort algorithm uses. Here’s the code he shows you: public static int[] array = {6, 1, 20, 10, 4}; public static int findMedian(int lo, int hi, int medianIndex) { int partitionIndex = partition(lo, hi); if (medianIndex == partitionIndex) return partitionIndex; if (medianIndex > partitionIndex) return findMedian(partitionIndex + 1, hi, medianIndex); else return findMedian(lo, partitionIndex - 1, medianIndex); } public static void main (String args[]) { System.out.println(findMedian(0, 4, 2)); } Upon reviewing the code, you find there is an error with it. Show your analysis by including the following: Show what the current code will print on the screen and explain why it is wrong Show the update(s) to the code you would make to fix the problem
Help on the following question?
Code Review Section
Your co-worker has developed a function to find the median value in an unsorted array with an odd number of elements. For arrays with an even number of elements, this function does not apply.
To normally find such a value would be to sort the array and then obtain the value at the middle index of the array. For example, [5 2 53 1 4], the median is 4 because when it is sorted, the array will be [1 2 4 5 53] and the value at the middle index is 4.
Your co-worker’s function uses the partition function that is the same function as the one the QuickSort
public static int[] array = {6, 1, 20, 10, 4};
public static int findMedian(int lo, int hi, int medianIndex)
{
int partitionIndex = partition(lo, hi);
if (medianIndex == partitionIndex)
return partitionIndex;
if (medianIndex > partitionIndex)
return findMedian(partitionIndex + 1, hi, medianIndex);
else
return findMedian(lo, partitionIndex - 1, medianIndex);
}
public static void main (String args[])
{
System.out.println(findMedian(0, 4, 2));
}
Upon reviewing the code, you find there is an error with it. Show your analysis by including the following:
- Show what the current code will print on the screen and explain why it is wrong
- Show the update(s) to the code you would make to fix the problem
Step by step
Solved in 5 steps with 2 images