您的位置:首页 > 其它

快速排序

2017-04-02 17:15 169 查看

快速排序

原理不讲了,看过很多遍了

最好和平均时间复杂度O(nlog2n),最坏是每次挑的哨兵都是最值(快速排序将不幸退化为冒泡排序)此时的时间复杂度O(n2)

空间复杂度最坏O(n) 最优及平均O(log2n)

不稳定(重复数据后往前)

import java.util.Arrays;

/**
* Created by xiaolong_ma on 2017/4/2.
*/

//堆排序
public class QuickSort {

public static void main(String[] args) {
int[] a={1,3,2,3,4};
quickSort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}

public static void quickSort(int[] array,int l,int r){
int flag=array[l]; //一般就是第一个array[0]
int start=l;
int end=r;

if(start>=end) //...这句话千万别忘了!!! 递归的收敛条件啊!!!
return;

while (start<end){

//从右往左找到第一个小的(先)这个在前面主要是因为要和flag换的话,只能换小的啊,start在前面就把大的换过去了
while (array[end]>=flag&&start<end)
end--;

//从左往右找到第一个大的
while (array[start]<=flag&&start<end)
start++;

//swap
if(start<end){
int temp = array[end];
array[end]=array[start];
array[start]=temp;
}
}

//最后start=end的时候
array[l]=array[start];
array[start]=flag;

quickSort(array,l,start-1);
quickSort(array,start+1,r);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  快速排序