The method medianOfThree
- returns the median of the first, center and last element in array
- sorts the first, center, and last element of the array, so they are in order EXCEPT places the center in the second to last position.
Examples:
INPUT: 1,2,3
RETURN:2
EFFECT:1,2,3INPUT: 3,2,1
RETURN:2
EFFECT:1,2,3INPUT: 2,3,1
RETURN:2
EFFECT:1,2,3INPUT: -2,-3,-8,1,20
RETURN:-2
EFFECT:-8,-3,1,-2,20INPUT: 15,20,5,10
RETURN:15
EFFECT:10,5,15,20
NOTE: when the center is moved to the second to last position, it doesn't matter where the value that was previously there goes (as long as it's still in the array). Though this probably isn't relevant. In fact, as long as the first, last and one before last are in the correct place, the rest of the elements can get scrambled.
Here is the code. I tested it, but since it is rather complex it was hard to test (need to check return value and array and think carefully of expected result). Any suggestions for tools that make testing code like this easier?
/*
*Sorts first, center and last element, swaps the new center element with the one before the new last and returns its value.
*/
public static int medianOfThree(int[] sample, int start, int end) {
if(sample.length < 3) {
throw new IllegalArgumentException("arrays of length three or greater");
}
int center = (int)Math.floor((end-start)/2);
if(sample[start] > sample[end])
swap(sample, start, end);
if(sample[start] > sample[center])
swap(sample, start, center);
if(sample[center] > sample[end])
swap(sample, center, end);
int secondLast = end - 1
swap(sample, center, secondLast );
return sample[secondLast];
}
//swaps two elements in array given their positions
private static void swap(int[] sample, int x, int y) {
int temp = sample[x];
sample[x] = sample[y];
sample[y] = temp;
}