算法-快排

public class ArithmeticImpl implements Arithmetic {
   @Resource
    private QuickSort quickSort;
    @Override
    public void quickSort(int[] arr) {
        quickSort.quickSort(arr);
    }
}
public class QuickSort {

public void quickSort(int[] arr) {
    quickSort(arr, 0, arr.length - 1);
}

private void quickSort(int[] arr, int left, int right) {
    //核心递归函数
    int pivot = 0;
    int cutoff = 0;
    int low = 0;
    int high = 0;
    if (cutoff <= right - left) {
        pivot = median(arr, left, right);//如果元素充分多,进入快排 Pivot = Median3( A, Left, Right );
        low = left;
        high = right - 1;
        while (true) {//将序列中比基准小的移到基准左边,大的移到右边
            while (arr[++low] < pivot) ;
            while (arr[--high] > pivot) ;
            if (low < high) {
                int temp = arr[low];
                arr[low] = arr[high];
                arr[high] = temp;
            } else {
                break;
            }
            int temp02 = arr[low];
            arr[low] = arr[high - 1];
            arr[high - 1] = temp02;

            quickSort(arr, left, low - 1);
            quickSort(arr, low + 1, right);
        }
    } else {
        InsertionSort(arr); /* 元素太少,用简单排序 */
    }
}

private int median(int[] arr, int left, int right) {
    int Center = (left + right) / 2;
    if (arr[left] > arr[Center])
        swap(arr[left], arr[Center]);
    if (arr[left] > arr[right])
        swap(arr[left], arr[right]);
    if (arr[Center] > arr[right])
        swap(arr[Center], arr[right]);
    /* 此时A[Left] <= A[Center] <= A[Right] */
    swap(arr[Center], arr[right - 1]); /* 将基准Pivot藏到右边*/
    /* 只需要考虑A[Left+1] … A[Right-2] */
    return arr[right - 1];  /* 返回基准Pivot */
}

private void swap(int i, int j) {
    int temp = i;
    i = j;
    j = temp;
}

private void InsertionSort(int[] arr) {
    for (int i = 1; i < arr.length; i++) {
        int temp = arr[i];
        int j = i;
        for (j = i; j > 0 && arr[j - 1] > temp; j--) {
            arr[j] = arr[j - 1];//初始值与第一个元素比较
        }
        arr[j] = temp;
    }
}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值