java之快速排序代码

快速排序

快速排序代码

	将最后一位作为准参数,分为两块,大于准参数的放在右边,小于准参数的放在左边,再从每一块中将最后一个作为准参数,以此类推进行。直接看代码
public class QuickSort {

    public static void main(String[] args) {
    }

    @Test
    public void test (){
    	// 当最后一位数是最小值或者最大值时,需要做一些特殊处理
        int[] arr = {4,8,2,1,6,7,5,9,10};
		// 随机选取准参数
 		int a =  (int)(Math.random()*(arr.length));
        System.out.println("a:" +a);;
        QuickSort(arr,0,a);
        // int a = 5;
        // QuickSort(arr,0,arr.length-1);
        print(arr);
    }

    public int Partition(int[] arr,int low,int high){
        // 获取基准数
        int piv = arr[high];
        int left = low;
        int right = high - 1;
        while (left < right){
            while (left <= right && arr[left] <= piv ){
                left++;
            }
            while (left <= right && arr[right] >=piv){
                right--;
            }
            if (left < right){
                swap(arr,left,right);
            }
        }
        if (arr[high] > arr[left]){
            return left;
        }
        swap(arr,left,high);
        return left;
    }

    public void QuickSort (int[] arr ,int low,int high) {
        if (low < high){
            int p = Partition(arr,low,high);
            QuickSort(arr,low,p-1);
            QuickSort(arr,p+1,high);
        }
        // 随机获取准参数时,后面一段的处理 或者以第一值为准参数时 
        else if (low == high && low <= arr.length){
            int p = Partition(arr,low,arr.length-1);
            QuickSort(arr,low,p-1);
            QuickSort(arr,p+1,arr.length-1);
        }
    }

    public static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void print(int[] arr){
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

结果如下: 每次选择的准参数不同,产生的结果相同

在这里插入图片描述
在这里插入图片描述

发现了一个bug
在这里插入图片描述
改良后的代码

    public void QuickSort (int[] arr ,int low,int high) {
        if (low < high){
            int p = Partition(arr,low,high);
            if (p ==0){
                QuickSort(arr,0,0);
            } else {
                QuickSort(arr,low,p-1);
                QuickSort(arr,p+1,high);
            }
        } else if (low == high && low <= arr.length){
            lToR(arr,low,arr.length - 1);
        }
    }

    public void lToR (int[] arr ,int low,int high){
        if (low < high) {
            int p = Partition(arr, low, high);
            lToR(arr, low, p - 1);
            if (p != arr.length) {
                lToR(arr, p + 1, high);
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值