排序算法---快速排序
寫給自己看的,防止忘記,儘量乾貨,初學者繞過。
快速排序採用的思想是分治思想。
給出一些無序數值,任意取一個作爲基準,基準的左邊都是比它小的,基準的右邊都是比他大的,遞歸快速排序即可。
public static void quickSort1(int[] num, int left, int right) {
if (num == null || num.length == 0 || left >= right) {
return;
}
int low = left, high = right;
int key = num[low]; // 任意選擇一個做爲key,接下來做的就是小於key的和大於key的互換,最後key放中間
while (low < high) {
while (num[high] > key) {
high--;
}
num[low] = num[high];
while (num[low] <= key && low < high) {//必須等號,不然相同數值會產生死循環
low++;
}
num[high] = num[low];
}
num[low] = key;//將key塞回
quickSort1(num, left, low - 1);
quickSort1(num, low + 1, right);
}
還可以改進,持續更新。。。