选择数组中的一个元素作为枢轴点(pivot)(通常选择数组最左边的元素),引入两个指针high,low通过开始从high的元素开始遍历,如果大于枢轴点则继续往左high--,如果小于枢轴点则将该元素放在low的位置,并开始从low位置开始遍历,如果小于枢轴点,low++,否则将该元素放在high位置,再从high开始遍历,如此交替,直到high=low,然后将枢轴点的值放在low上,这样完成一趟排序使得low左边的元素小于low所在的元素,low右边的元素大于low所在元素,然后对两边的元素进行递归快排。
代码:
public class QuickSort {
public static int[] quickSort(int[] A,int left,int right)
{
if(left<right)
{
int key=A[left];
int low=left;
int high=right;
while(low<high)
{
while(low<high&&A[high]>=key)
{
high--;
}
A[low]=A[high];//比中轴小的记录移到低端
while(low<high&&A[low]<key)
{
low++;
}
A[high]=A[low];//比中轴大的记录移到高端
}
A[high]=key;//A[low]=key;
print(A);
quickSort(A,left,low-1);
quickSort(A,low+1,right);
}
return A;
}
private static void print(int[] A)
{
for(int i=0;i<A.length;i++)
System.out.print(A[i]+" ");
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A= {9,10,6,4,29,34,25,14,18,17,8,5};
int n=12;
System.out.println("快排过程中序列的变化:");
int[] ans=QuickSort.quickSort(A, 0, n-1);
System.out.println("快速排序后的序列:");
for(int i=0;i<n-1;i++)
System.out.print(ans[i]+" ");
System.out.print(ans[n-1]);
}
}
测试结果:
快排过程中序列的变化:
5 8 6 4 9 34 25 14 18 17 29 10
4 5 6 8 9 34 25 14 18 17 29 10
4 5 6 8 9 34 25 14 18 17 29 10
4 5 6 8 9 10 25 14 18 17 29 34
4 5 6 8 9 10 25 14 18 17 29 34
4 5 6 8 9 10 17 14 18 25 29 34
4 5 6 8 9 10 14 17 18 25 29 34
快速排序后的序列:
4 5 6 8 9 10 14 17 18 25 29 34
由上述代码以及排序运行结果可以知道,相较于一般地比较排序,快速排序的效率比较高,其时间复杂度为O(nlogn),而且是就地排序,不需要额外的辅助空间,如果high指针往回遍历的时候,如果遇到与枢轴值相等的值,若此时不交换位置,继续遍历的话,可以做到排序算法的稳定性,使得相等的元素能够保持在原序列中的先后顺序。
转发请注明:转自http://blog.csdn.net/carson0408/article/details/78654619