我有以下陣列:快速排序劃分
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)必須在左邊,並且每個元素> pi vot元素必須在右側。但是,爲什麼12離開到7?