您的位置:首页 > 产品设计 > UI/UE

交互设计算法基础(3) - Quick Sort

2017-09-16 11:51 232 查看
1 int pivotIndex, pivot, swapIndex;
2
3 void swap(int[] arr, int x, int y) {
4   int temp = arr[x];
5   arr[x] = arr[y];
6   arr[y] = temp;
7 }
8
9 void quickSort(int[] arr, int start, int end) {
10   if (end <= start) return;
11
12   pivotIndex = (start + end)/2;
13   pivot = arr[pivotIndex];
14   swap(arr, pivotIndex, end);
15   swapIndex = start;
16   for (int i = start; i < end; i++) {
17     if (arr[i] <= pivot) {
18       swap(arr, i, swapIndex);
19       ++swapIndex;
20     }
21   }
22   swap(arr, swapIndex, end);
23
24   quickSort(arr, start, swapIndex-1);
25   quickSort(arr, swapIndex+1, end);
26 }
27
28 void draw() {
29   noLoop();
30   int[] arr = {10, 5, 2, 3};
31   quickSort(arr, 0, arr.length-1);
32   println(arr);
33 }


快速排序,说白了就是快啦,不过有两种实现方式,一种普通,一种In-place,后面的比前面的占用较少空间。

快排用分治法解决。

最佳时间复杂度:O(nlog n)

平均时间复杂度:O(nlog n)

最差时间复杂度:O(n2)

空间复杂度:一般版本O(n),In-place O(log n)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: