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

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);
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值