快速排序是常用到的排序算法之一,也是最优秀的排序算法之一。平均时间复杂度为O(n log),最坏时间复杂度为O(n^2)(此情况比较特殊,数组刚好是倒序的)。
采用了分治的思想。选择一个元素作为基准,将小于基准的数放在左边,大于基准的数放在右边,然后将基准放在正确的位置。在基准左边的分组和右边的分组用同样的方法,进行递归快速排序,最后得到排序后的数组。
public class QuitSort {
public static void main(String[] args) {
int arry[]={5,4,23,7,41,1,9,67,8,32};
for(int a:arry){
System.out.print(a+",");
}
System.out.println();
QuickSort(arry,0,arry.length);
for(int a:arry){
System.out.print(a+",");
}
}
public static void QuickSort(int[] arry,int start,int end){
if(start<end){
int pivote =arry[start];//初始化基准
int i=start,j;//初始化i,j
for(j=start+1;j<=end;j++){
if(arry[j]<pivote ){
int temp=arry[j];
arry[j]=arry[i+1];
arry[i+1]=temp;
i++;
}
}
arry[start]=arry[i];
arry[i]=pivote ;
QuickSort(arry,start,i-1);
QuickSort(arry,i+1,end);
}
}
}