快速排序算法
注:学习心得,仅供参考。如有错误,请不吝指教。
概述
快速排序算法C.R.A.Hoare于1962年提出的一种划分交换排序。该算法采用了分治的策略,通常又称为分治法(Divied-and-ConquerMethod)。
基本思想
分治法的思想:将原问题分解为若干个更小规模的但结构与原问题相似的子问题,递归地解这些子问题,然后将这些子问题的解组合为原问题的解。
快速排序的思想:设当前待排序的区间为R[low...high],利用分治法实现快速排序。主要有三个步骤:1原问题分解;2子问题求解;3组合子问题的解。
算法特点
快速排序法是一种不稳定的排序算法,其平均时间复杂度为O(n*log(n^2));最差情况下时间复杂度为O(n^2)。
算法实现
源代码:
public class QuickSort {
//快速排序算法
public static void qsort_asc(int source[],int low, int high){
int i,j,x;
if(low<high){//对无序R[low,...,high]快速排序
i = low;
j = high;
x = source[i];//初始化基准
//划分算法实现
while(i<j){//从区间两端交替向中间扫描,直至i=j
while(i<j && source[j]>x){
j--;//从右向左扫描,找到第一个小于基准x的值source[j]
}
if(i<j){
source[i] = source[j];//更新基准
i++;
}
while(i<j && source[i]<x){
i++;
}
if(i<j){
source[j] = source[i];
j--;
}
}
source[i] = x;
qsort_asc(source,low,i-1);//对左区间递归排序
qsort_asc(source,i+1,high);//对右区间递归排序
}
}
public static void main(String[] args) {
int[] a= {4,2,1,6,3,8,0,-5,1,9};
qsort_asc(a,0,a.length-1);
for(int i=0;i<10;i++)
System.out.printf("%d ",a[i]);//等价于
// System.out.print(a[i]+" ");
}
}
运行结果:
-5 0 1 1 2 3 4 6 8 9