【排序算法】快速排序(java实现)

来源:互联网 发布:二级建造师网络教育 编辑:程序博客网 时间:2024/06/16 16:08

1.基本思想:

它采用了一种分治的策略,通常称为分治法。

分治法思想:将原问题分解为若干个规模更小但结构与原问题相似的子问题。递归地解这些子问题,然后将这些子问题的解组合为原问题的解。

对于数组A, 随机选择一个元素作为基准数pos,一般为第一个元素或最后一个元素。

将该数组分为两堆A[0,pos_index-1]  和 A[pos_index+1,n],一堆元素全都小于pos ,另一堆元素全都大于pos ,pos_index 为基准素的下标。

按照分治思想,左右两堆分别进行快排递归操作,即QuickSort(A, 0, pos_index -1) 和 QuickSort(A,  pos_index +1 , n)  。

1)一趟排序过程:


2)整个排序过程:


2.算法分析:

平均时间复杂度: O(nlog2n)      最坏(有序情况下):O(n^2)

空间复杂度:   O(logn)     最坏  O(n)

稳定性:                不稳定

3.算法实现:

<span style="white-space:pre"></span>public static int partition(int[] array,int l, int r){int pos = array[l];while(l<r){//从右往左找出比基准数小的下标rwhile(l < r && array[r] >= pos) r--;// 与基准数交换int tmp =  array[r];array[r] = array[l]; array[l] = tmp; //从左往右找出比基准数大的下标lwhile(l < r && array[l] <= pos) l++;tmp =  array[r];array[r] = array[l]; array[l] = tmp; }return l;}public static void QuickSort(int[] array,int l, int r){if(l<r){//确定基准数在一次遍历后的下标,左右两边递归进行int t = partition(array,l,r);QuickSort(array,l,t-1);QuickSort(array,t+1,r);}}

4.算法优化:

1.只对长度大于k的子序列递归调用快速排序,让原序列基本有序,然后再对整个基本有序序列用插入排序算法排序。
详见  http://blog.csdn.net/naruto_ahu/article/details/8192039 

2. 通过随机选择初始基准数,使得当面对有序序列时,时间复杂度也为O(nlog2n);同时,去掉了没有必要的对基准数值的来回交换,只需要最后的时候放到目标位置上就可以了。
<span style="white-space:pre"></span>public static int partition1(int[] array,int l, int r){int index  = (int) (Math.random() % (r - l+1) + l);int pos = array[ (int) (Math.random() % (r - l+1) + l)];while(l<r){//从右往左找出比基准数小的下标rwhile(l < r && array[r] >= pos) r--;// 与基准数交换array[index] = array[r]; index = r;//从左往右找出比基准数大的下标lwhile(l < r && array[l] <= pos) l++;array[index] = array[l]; index = l;}array[l] = pos;  // 将基准数放入最后所求分割位置return l;}public static void QuickSort(int[] array,int l, int r){if(l<r){//确定基准数在一次遍历后的下标,左右两边递归进行int t = partition1(array,l,r);QuickSort(array,l,t-1);QuickSort(array,t+1,r);}}



0 0
原创粉丝点击