您的位置:首页 > 其它

排序-快速排序-优化-使用插入排序

2016-01-22 09:08 393 查看
package xwq.sort;

import xwq.util.In;
import xwq.util.StdOut;
import xwq.util.StdRandom;

/**
* 使用插入排序对快速排序进行优化
* 大数组使用快速排序递归切分,小数组使用插入排序
* @author batman
*
*/
public class QuickSortInsert {

//M的最佳值是和系统相关的,但是5-15之间的任意值在大多数情况下都能令人满意
private static int M = 10;

public static void sort(int[] a) {
partition(a, 0, a.length - 1);
}

//数组划分
private static void partition(int[] a, int low, int high) {
if(low>=high)   return;

//如果待排序数组长度小于等于M个数,使用插入排序
if((high-low+1) <= M)  {
insertSort(a,low,high);
return;
}

int pos = StdRandom.uniform(low, high + 1);//随机生成一个基准位置
int pivot = a[pos];//基准值
int l = low,h = high;
swap(a, low, pos);
while (l < h) {
while (l < h && a[h] >= pivot) h--;
if (l < h)  a[l++] = a[h];
while (l < h && a[l] <= pivot) l++;
if (low < high) a[high--] = a[low];
}
a[low] = pivot;

partition(a,low,l-1);
partition(a,l+1,high);
}

//插入排序
private static void insertSort(int[] a,int low,int high) {
for(int i = low + 1;i <= high;i++) {
int t = a[i];//待插入值
int j = i - 1;//从当前位置的上位开始比较
while(j >= low && a[j] > t){
a[j+1] = a[j];
j--;
}
a[j+1] = t;
}
}

private static void swap(int a[], int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}

public static void print(int a[]) {
for (int i = 0; i < a.length; i++)
StdOut.print(a[i] + " ");
StdOut.println();
}

//测试函数
public static void main(String[] args) {
int[] a = In.readInts(args[0]);
sort(a);
print(a);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: