Skip to content

Instantly share code, notes, and snippets.

@TPei
Last active December 26, 2015 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TPei/7192129 to your computer and use it in GitHub Desktop.
Save TPei/7192129 to your computer and use it in GitHub Desktop.
/**
* given three positions in an array a,
* checks which of those array elements is the median
* and returns the corresponding index
* if multiple elements are equal, returns second if appropriate
*
* @param first index of first element to compare
* @param second index of second element to compare
* @param third index of third element to compare
* @return the index of the found median element
*/
private int medianOfThree(int first, int second, int last){
if (a[first] >= a[second]) {
if (a[second] >= a[last])
return second;
else if (a[first] > a[last])
return last;
else
return first;
}
else { // a[second] > a[first]
if (a[first] > a[last])
return first;
else if (a[second] > a[last])
return last;
else
return second;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment