交互设计算法基础(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)
相关文章推荐
- 交互设计算法基础(4) - Hash Table
- 交互设计算法基础(1) - Binary Search
- 基础排序算法之快速排序(Quick Sort)
- 【算法设计与分析基础】8、背包问题
- Android基础知识之四大组件Activity(三)多个Activity交互的生命周期与设计思想
- 算法设计与应用基础作业第一周
- 算法设计与应用基础:第十三周(2)
- 计算方法 实验一 算法设计基础
- java基础—算法设计
- 算法设计与应用基础-第十一周
- 学点PYTHON基础的东东--数据结构,算法,设计模式---单向链表
- 算法设计与应用基础:第三周
- 算法设计与应用基础:第十四周(2)
- 算法设计与应用基础:第十二周(1)
- 算法设计与应用基础系列8
- 算法设计与应用基础-第九周&第十周
- 算法设计与应用基础:第一周(3)
- 《算法竞赛入门经典——训练指南》第一章—算法设计基础
- 基础排序算法之快速排序(Quick Sort)
- 算法设计与应用基础: 第三周(2)