There is something wrong with the findMedian Java function below. This one is de
ID: 3840048 • Letter: T
Question
There is something wrong with the findMedian Java function below. This one is designed to only deal with an odd number of array elements. The median value of an array is the element value of the middle index of the array when it is sorted. For example, {5, 2, 53, 1, 4}, the median is 4 because when it is sorted, the middle index has an element value of 4.
In this exercise, the code uses the partitionIt function which is the same function the quickSort algorithm uses. After reviewing the code, answer the following questions:
1) What is the expected output of this particular program?
2) What changes to the code are needed to fix the issue(s)?
public static int[] array = {5, 2, 53, 10, 4};
public static int findMedian(int lo, int hi, int medianIndex)
{ int partitionIndex = partitionIt(lo, hi); if (medianIndex == partitionIndex) return array[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)); }
Explanation / Answer
Ans.
1)
According to program: if medianIndex > partitionIndex, then we are going to left half of the array(from partation point), so it always result in java.lang.ArrayIndexOutOfBoundsException because at a point "hi" value will be -1 .
2)
Fixed code:
public static int findMedian(int lo, int hi, int medianIndex)
{
int partitionIndex = partitionIt(lo, hi);
if (medianIndex == partitionIndex)
return array[partitionIndex];
if (medianIndex > partitionIndex)
return findMedian(partitionIndex + 1, hi, medianIndex);
else
return findMedian(lo, partitionIndex - 1, medianIndex);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.