1.快速排序思想
快速排序采用了分治的思想,通过多次排序,每次排序都将待排序数组分为两部分,其中一部分记录的关键字均比另一部分记录的关键字小,如此反复,最终使整个数组达到有序。
2.快速排序的三个步骤:
(1)选择基准:在待排序列中,选出一个记录的关键字作为基准
(2)分割:将待排序列分割成两个部分,基准左边的部分都比基准小,基准右边的部分都比基准大。
(3)对分割开的两个部分序列进行递归快排,直到序列中只有一个元素或者序列为空。
3.快速排序的特点:极快,数据移动少。但是如果数组已经有序,那么快速排序将沦为起泡排序,时间复杂度为O(n2).如果每次选取的基准都为中间值,那么就是最好的情况,时间复杂度为O(nlogn),这是因为基准为中间值时,递归树是平衡的,在递归划分时能进行最少次数的划分。
快速排序是不稳定的排序方法。
4.算法JAVA实现
1 public class QuickSort{ 2 public static int getMiddle(int[] num,int i,int j){ 3 4 int low=i-1,high=j-1,temp=num[i-1]; 5 while(low<high){ 6 while(low<high && num[high]>=temp){ 7 high--; 8 } 9 num[low++]=num[high]; 10 while(low<high && num[low]<temp){ 11 low++; 12 } 13 num[high--]=num[low]; 14 } 15 num[low]=temp; 16 return low; 17 } 18 public static void QuickSort(int[] num,int i,int j){ 19 if(num==null ||(j-i+1<2)){ 20 return; 21 } 22 while(i<j){ 23 int temp=getMiddle(num,i,j); 24 QuickSort(num,i,temp); 25 i=temp+2; 26 //QuickSort(num,temp+2,j);过多递归占用大量堆栈,同时入栈退栈浪费大量时间,代为迭代 27 } 28 } 29 public static void main(String[] args){ 30 int[] num={5,16,4,20,2,9,3,12,55,13}; 31 int length=num.length; 32 QuickSort(num,1,length); 33 for (int i=0;i<num.length;i++ ) { 34 System.out.println(num[i]); 35 } 36 } 37 }
5.优化
http://blog.youkuaiyun.com/insistgogo/article/details/7785038,很推荐这篇对快速排序算法的优化文章,里面讲解了主要的几种快排优化方式,包括(1)基准选择的优化、(2)判断待续序列长度,满足条件使用其他简单排序算法提高效率、(3)一次分割结束后,聚集与基准相等元素,不再参与下次分割、(4)优化递归的操作,缩减堆栈深度等