另一种可能性是将方法分成两部分,一个划分为 [<= pivot, > pivot],另一个将结果的第一部分划分为 [< pivot, >= pivot]。
public static int partitionLE(double[] a, int left, int right, double pivot) {
double x, y;
if (left >= right) return left;
for (;;) {
while ((x = a[left]) <= pivot) {
if (++ left >= right) return left;
}
while ((y = a[right-1]) > pivot) {
if (left >= -- right) return left;
}
if (left < right) {
a[left] = y;
a[right-1] = x;
} else {
return left;
}
}
}
public static int partitionLT(double[] a, int left, int right, double pivot) {
double x, y;
if (left >= right) return left;
for (;;) {
while ((x = a[left]) < pivot) {
if (++ left >= right) return left;
}
while ((y = a[right-1]) >= pivot) {
if (left >= -- right) return left;
}
if (left < right) {
a[left] = y;
a[right-1] = x;
} else {
return left;
}
}
}
public static int partition(double[] a, int left, int right, double pivot) {
int lastP = partitionLE(a, left, right, pivot);
int firstP = partitionLT(a, left, lastP, pivot);
if (firstP < lastP) {
return firstP;
} else {
return ~firstP;
}
}