快速排序java实现


快速排序java实现

假设一个数组 int i[] = {6,5,0,7,9,6,1,4,5,12,10,3,8,19};
用快速排序法进行从小到大排序。
原理为寻找一个基准数,一般为第一个数。然后将这个数字取出。从后往前寻找比它小的数,放到前面。这时又有了一个空位。在从前往后寻找比它大的数,放进之前的位置,不断重复。

在这里插入图片描述


使用步骤

核心代码:

  int start = 0;
  int x = i[start];
  int end = i.length-1;
        while (start<end){
            while (start<end&&i[end]>x){
                end--;
            }
            if(start<end){
                i[start] = i[end];
                start++;
            }
            while (start<end&&i[start]<x){
                start++;
            }
            if(start<end){
                i[end] = i[start];
                end--;
            }
        }
        i[start]=x;

运行一次之后:

[3, 5, 0, 5, 4, 1, 6, 6, 9, 12, 10, 7, 8, 19]

运行一次之后,用递归不断调用。
完整实现代码:

        int i[] = {6,5,0,7,9,6,1,4,5,12,10,3,8,19};
        int start = 0;
        int end = i.length-1;
        quickSort(i,start,end);
        System.out.println(Arrays.toString(i));
    }
    public static void quickSort(int[] i,int start,int end){
        if(start<end){
            int middle = middles(i,start,end);
            quickSort(i,start,middle-1);
            quickSort(i,middle+1,end); 
        }
    }
    public static int middles(int[] i,int start,int end){
        int x = i[start];
        while (start<end){
            while (start<end&&i[end]>x){
                end--;
            }
            if(start<end){
                i[start] = i[end];
                start++;
            }
            while (start<end&&i[start]<x){
                start++;
            }
            if(start<end){
                i[end] = i[start];
                end--;
            }
        }
        i[start]=x;
        return start;
    }

输出

[0, 1, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10, 12, 19]

总结

快速排序在绝大部分时候优于冒泡排序。应当优先使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值