1
快速排序是在待排序的數組中找到一個數作爲分隔符,大於這個數的放到一起,小於這個數的放到一起。一次進行遞歸直到排序結束
2
核心代碼
public void recQuickSort(int left, int right) {
if (left - right >= 0) {
return;
} else {
int pivot = arr[right];
int partition = partitionIt(left, right, pivot);
recQuickSort(left, partition - 1);// 前一部分劃分;
recQuickSort(partition+1, right);// 後一部分劃分;
}
}
獲取分隔符以及進行換位的代碼
public int partitionIt(int left, int right, int val) {
int lefttemp = left - 1;
int righttemp = right+1;
while (true) {
// 找小的 左到右
while (lefttemp < right && arr[++lefttemp] <= val) {
}
// 找小的 右到左
while (righttemp > left && arr[--righttemp] >= val) {
}
if (lefttemp >= righttemp) {
break;
} else {
swap(lefttemp, righttemp);
}
}
swap(lefttemp, right);
return lefttemp;
}
public void swap(int dex1, int dex2) {
int temp = arr[dex1];
arr[dex1] = arr[dex2];
arr[dex2] = temp;
}