相关特点
- 最坏时间复杂度为o(n^2)
- 最好时间复杂度为o(nlogn)
- 平均时间复杂度为o(nlogn)
- 平均空间复杂度为o(logn)
- 不稳定
基本思想
通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。
算法描述
快速排序使用分治法来把一个串(list)分为两个子串(sub-lists)。具体算法描述如下:
- 从数列中挑出一个元素,称为 “基准”(pivot);
- 重新排序数列,所有元素比基准值小的摆放在前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;
- 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
图解描述以字表第一个记录为枢轴的分区操作过程

代码实现
/**
* 思路同大话数据结构
* @author Dan
*
*/
public class QuickSort1 {
/**
* 递归实现快速排序
*/
public static void quickSort(int[] A,int startIdx,int endIdx){
int pivot; //设置枢轴值(关键字)
if(startIdx < endIdx){
pivot = partition(A,startIdx,endIdx); //将待排序数组一分为二,返回枢轴值pivot
quickSort(A,startIdx,pivot-1); //对于弟子表递归排序
quickSort(A,pivot+1,endIdx); //对高子表递归排序
}
}
/**
* 获取枢轴位置
* @param : @param A 待排序数组
* @param : @param startIdx 开始坐标
* @param : @param endIdx 结束坐标
* @param : @return 枢纽坐标位置
* @Version : vx.x
*/
public static int partition(int[] A,int startIdx,int endIdx){
int pivotkey;
pivotkey = A[startIdx]; //这里用子表的第一个记录做枢轴记录
while(startIdx < endIdx){
while(startIdx < endIdx && A[endIdx] >= pivotkey){
endIdx--;
}
swap(A,startIdx,endIdx);
while(startIdx < endIdx && A[startIdx] <= pivotkey){
startIdx++;
}
swap(A,startIdx,endIdx);
}
return startIdx;
}
/**
* 交换数组a,b位置的数据
*/
static void swap(int[] A , int a, int b){
int temp = A[a];
A[a] = A[b];
A[b] = temp;
}
public static void main(String[] args) {
int[] A = new int[]{23,5,17,2,48,3,7,13};
quickSort(A, 0, A.length-1);
for (int i = 0; i < A.length; i++) {
System.out.print(A[i]+" ");
}
}
}
137

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



