Skip to content

Instantly share code, notes, and snippets.

@DavidCulpepper
Created April 13, 2012 09:29
Show Gist options
  • Save DavidCulpepper/2375405 to your computer and use it in GitHub Desktop.
Save DavidCulpepper/2375405 to your computer and use it in GitHub Desktop.
MEDIAN {
@Override
public int getPivotIndex(int firstIndex, int lastIndex, int[] array) {
int middleIndex = (firstIndex + lastIndex) / 2;
int firstValue = array[firstIndex];
int lastValue = array[lastIndex];
int middleValue = array[middleIndex];
numComparisons = 0;
numComparisons++;
if (middleValue > firstValue) {
numComparisons++;
if (middleValue < lastValue) {
return middleIndex;
} else {
numComparisons++;
if (firstValue < lastValue) {
return lastIndex;
} else {
return firstIndex;
}
}
} else {
numComparisons++;
if (firstValue < lastValue) {
return firstIndex;
} else {
numComparisons++;
if (middleValue < lastValue) {
return lastIndex;
} else {
return middleIndex;
}
}
}
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment