/** * 标准快排 * 【注意】 * 最左边为基准数(flag)的时候,从右开始往前遍历。 */ publicclassKuaisupaixu{ publicstaticvoidquicksort(int[] arr, int left, int right){ if (left > right) { return; } int flag = arr[left]; int l = left; int r = right; int temp;
while (l != r) { while (arr[r] >= flag && l < r) { //【重点】 r -= 1; } while (arr[l] <= flag && l < r) { l += 1; } temp = arr[r]; arr[r] = arr[l]; arr[l] = temp;
} arr[left] = arr[l]; arr[l] = flag;
quicksort(arr, left, l - 1); quicksort(arr, l + 1, right); }
publicstaticvoidmain(String[] args){ int[] a = {9, 2, 1, 5, 4, 8, 7, 6, 1, 0}; quicksort(a, 0, a.length - 1); for (int i : a) { System.out.print(i + " "); } } }
scala
1 2 3 4 5 6 7 8 9 10 11 12
/** * 快排 * 时间复杂度:平均时间复杂度为O(nlogn) * 空间复杂度:O(logn),因为递归栈空间的使用问题 */ defquickSort(list: List[Int]): List[Int] = list match { caseNil => Nil caseList() => List() case head :: tail => val (left, right) = tail.partition(_ < head) quickSort(left) ::: head :: quickSort(right) }
/** * @param arr 排序的原始数组 * @param left 左边有序序列的初始索引 * @param mid 中间索引 * @param right 右边索引 * @param temp 做中转的数组 */ publicstaticvoidmerge(int[] arr, int left, int mid, int right, int[] temp){
int i = left; // 初始化i, 左边有序序列的初始索引 int j = mid + 1; //初始化j, 右边有序序列的初始索引 int t = 0; // 指向temp数组的当前索引
//(一) //先把左右两边(有序)的数据按照规则填充到temp数组 //直到左右两边的有序序列,有一边处理完毕为止 while (i <= mid && j <= right) {//继续 //如果左边的有序序列的当前元素,小于等于右边有序序列的当前元素 //即将左边的当前元素,填充到 temp数组 //然后 t++, i++ if (arr[i] <= arr[j]) { temp[t] = arr[i]; t += 1; i += 1; } else { //反之,将右边有序序列的当前元素,填充到temp数组 temp[t] = arr[j]; t += 1; j += 1; } }
//(二) //把有剩余数据的一边的数据依次全部填充到temp while (i <= mid) { //左边的有序序列还有剩余的元素,就全部填充到temp temp[t] = arr[i]; t += 1; i += 1; }
while (j <= right) { //右边的有序序列还有剩余的元素,就全部填充到temp temp[t] = arr[j]; t += 1; j += 1; }
//(三) //将temp数组的元素拷贝到arr //注意,并不是每次都拷贝所有 t = 0; int tempLeft = left; // //第一次合并 tempLeft = 0 , right = 1 // tempLeft = 2 right = 3 // tL=0 ri=3 //最后一次 tempLeft = 0 right = 7 while (tempLeft <= right) { arr[tempLeft] = temp[t]; t += 1; tempLeft += 1; } } }
scala
1 2 3 4 5 6 7 8 9 10 11 12
/** * 快排 * 时间复杂度:O(nlogn) * 空间复杂度:O(n) */ defmerge(left: List[Int], right: List[Int]): List[Int] = (left, right) match { case (Nil, _) => right case (_, Nil) => left case (x :: xTail, y :: yTail) => if (x <= y) x :: merge(xTail, right) else y :: merge(left, yTail) }