public class QuickSort {
public void sort(int[] a) throws Exception{
if((a==null) || (a.length==0)){
throw new Exception();
}
quickSort(a, 0, a.length-1);
}
public void quickSort(int[] a, int left, int right) throws Exception{
if(left >= right){
return;
}
int p = partition(a, left, right);
quickSort(a, left, p-1);
quickSort(a, p+1, right);
}
private int partition(int[] a, int left, int right){
int mid = a[right];
int p = left;
for(int i=left; i<right; i++){
if(a[i] < mid){
swap(a, i, p);
p++;
}
}
swap(a, p, right);
return p;
}
private void swap(int[] a, int p1, int p2){
int temp = a[p1];
a[p1] = a[p2];
a[p2] = temp;
}
/**
* @param args
*/
public static void main(String[] args) {
QuickSort sorter = new QuickSort();
int[] a = {7,2,4,8,3,5,1,9,0,6};
try {
sorter.sort(a);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Tools.printArray(a);
}
}
怎么保证快速排序的最差复杂度为O(n*lgn),这就需要保证每次选出的参考数是中位数,怎么保证在线性时间里选出中位数?参考算法导论的相关章节。
本文探讨快速排序算法中如何通过选取中位数优化其最差情况复杂度至O(n*lgn)。重点介绍在线性时间内找出中位数的方法,并解析其实现细节。
18万+

被折叠的 条评论
为什么被折叠?



