挑战常见排序(四)——快速排序

快速排序   原地、不稳定排序、O(nlogn)、o(n)

自己对快速排序做了一个小分类:单路快排、二路快排


1.单路快排

public class FastSort {
    public static void Fast(int[] arr) {
       int n = arr.length;
       if(n <= 1)
           return;
       quickSortInternal(arr,0,n-1);//快排内部
    }
    public static void quickSortInternal(int[] arr,int l,int r){
        if(r <= l)  //右边大于等于左边返回
            return;
        int q = partition(arr,l,r);
        quickSortInternal(arr,l,q-1); //递归左边
        quickSortInternal(arr,q+1,r); //递归右边
    }
    public static int partition(int[] arr,int l, int r){
        int randomNum = (int) (Math.random()*(r-l+1)+l);//任意取一个随机数
        Swap(arr,l,randomNum);//将取到的随机数与第一个值交换
        int values = arr[l]; //最左边第一个数
        int j = l; //第一个数下标
        int i = l+1; //第二个数下标
        for(;i <= r;i++){
            if(arr[i] < values){ //若此数比基准数小 和j+1交换
                Swap(arr,i,j+1);
                j++;
            }
        }
        Swap(arr,j,l);
        return j;
    }
    public static void Swap(int[] arr,int a,int b){
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
     }

}

2.双路快排 

 

 

public class TwoFastSort {
    public static void TwoFast(int[] arr) {
        int n = arr.length;
        if (n <= 1)
            return;
        TwoFastSort(arr, 0, n - 1);
    }

    public static void TwoFastSort(int[] arr, int l, int r) {
        if (l >= r)
            return;
        int q = TwoPartition(arr, l, r);
        TwoFastSort(arr, l, q - 1);
        TwoFastSort(arr, q + 1, r);
    }

    public static int TwoPartition(int[] arr, int l, int r) {
        int values = arr[l];//基准值保存
        int i = l + 1;
        int j = r;
        while (true) {
            while (i <= r && arr[i] < values)
                i++;
            while (j >= l + 1 && arr[j] > values)
                j--;
            if (i > j) {
                break;
            }
            TwoSwap(arr, i, j); //找到了大于基准数的值和小于基准数的值 ,交换两数
            i++;
            j--;
        }
        TwoSwap(arr, l, j);
        return j;
    }

    public static void TwoSwap(int[] arr, int a, int b) {
        int temp = arr[b];
        arr[b] = arr[a];
        arr[a] = temp;
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值