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

 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)

posted on 2017-09-16 11:51  o0松鼠0o  阅读(247)  评论(0编辑  收藏  举报