快速排序,通常排序算法中的最佳选择,其期望时间复杂度为O(NlogN),最坏情况为O(N^2)。而且快速排序能进行就地排序,不需要像merge sort样,使用临时数组。
算法简介
快速排序和归并排序(merge sort)类似,都是采用分治法(divide and conquer)。与归并排序不同的是,快速排序不是讲数据平分为两半,而是将数据分为比参参考值小的一组合比参考值大的一组。
标准的快速排序中参考值选取为a[length - 1]。但是这样性能不稳定。为了能取得最好的平均效率,通常采用随机法,随机在数据中取一个数作为参考值。下面的代码就是按这种方式实现的。
算法:
假设当前数组的长度为(r + 1)。
1,随机选择一个数a[i],swap(a[i],a[r]);
2,定义两个指针i,j= 0;i表示当前比参考值大的一组数据的开始位置,j表示当前比参考值大的一组数据的结束位置。
3,一个循环,while(j <r )每次j++,(如果当前的数a[j]<参考值,swap(a[i],a[j]),i++)
下面的一张图是从MIT《算法导论》上截来的,i,j意义略有不同,不过最重要的是理解算法的思想。
代码
package sorting;
public class Data {
/**
* generate an unsorted array of length n
* @param n length
* @param max the maximum integer element of this array
* @return an unsorted array consists of elements range from 1 to max
*/
public static int[] getArray(int n, int max){
int[] result = new int[n];
for(int i =0; i < n; i++){
result[i] = (int)(Math.random() * max + 1);
}
return result;
}
/**
* print the array
* @param arg array
*/
public static void printArray(int[] arg){
StringBuffer temp = new StringBuffer();
for(int i = 0; i < arg.length; i++){
temp.append(arg[i] + "\t");
}
System.out.println(temp);
}
}
package sorting;
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
QuickSort qs = new QuickSort();
int[] data = Data.getArray(10, 100);
System.out.print("Source data:\t");
Data.printArray(data);
qs.quickSort(data,0,data.length - 1);
System.out.print("Sorted data:\t");
Data.printArray(data);
}
public void quickSort(int[] arg,int begin, int end){
if(begin < end){
int length = end - begin + 1;
int r = begin + length - 1;
int p = begin + (int)(Math.random() * length);
//switch arg[p] and arg[r]
int temp = arg[r];
arg[r] = arg[p];
arg[p] = temp;
int i = begin;
int j = begin;
while(j < r){
if(arg[j] < arg[r]){
temp = arg[i];
arg[i] = arg[j];
arg[j] = temp;
i++;
}
j++;
}
//switch arg[i] and arg[r].
// in fact, this switch can be done in the above loop
temp = arg[r];
arg[r] = arg[i];
arg[i] = temp;
quickSort(arg,begin, i - 1);
quickSort(arg, i+ 1,end);
}
}
}

本文深入探讨快速排序算法的核心思想、实现细节及其优化策略,包括随机选择基准元素的方法,详细解释了算法的工作流程和复杂度分析。通过代码示例展示如何在Java环境下实现快速排序,并比较与归并排序的不同之处。
9万+

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



