我有以下数组:
int[] arr = { 19, 4, 2, 3, 9, 2, 10, 2, 7, 12, 5, 16, 8, 3, 11, 14, 0, 5 };
现在我使用快速排序的分区来对具有枢轴元素 7 的数组进行分区:
public static void partition(int[] arr, int low, int high) {
int pivot = arr[low + (high - low) / 2];
int i = low;
int j = high;
while (i <= j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (arr[i] < pivot) {
i++;
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (arr[j] > pivot) {
j--;
}
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
if (i <= j) {
swap(arr, i, j);
i++;
j--;
}
}
}
我对结果感到困惑:
5 4 2 3 0 2 3 2 5 12 7 16 8 10 11 14 9 19
我认为每个元素 <= pivot (7) 必须在左侧,并且每个元素 > 比枢轴元素必须在右侧。但是为什么 12 剩下 7 呢?