Java实现快速排序

Java实现快速排序

public class demo01 {
    public static void main(String[] args) {
         int[] a = {19, 95, 9, 17, 1, 8};
       // int[] a = {-1, 15, -8, 25};
        showList(a);
        quickSort(a, 0, a.length - 1);
        showList(a);
    }

    /*
     * 快排算法
     * */
    public static void quickSort(int[] array, int left, int right) {
        if (left > right) {
            return;
        }
        int base = array[left];//定义基准;
        int i = left;
        int j = right;
        while (i != j) {
            //将最开始base处看成空
            //先从右边找,如果数组比base小则停止
            while ((array[j] >= base) && (i < j)) {
                j--;
            }
            //找到小于base的数,放到空位置
            array[i] = array[j];
            while (array[i] < base && i < j) {
                i++;
            }
            //找到大于base的数,放到空位置
            array[j] = array[i];
        }
        array[i] = base;
        quickSort(array, left, i - 1);
        quickSort(array, i + 1, right);
    }

    /*
     * 展示数组元素
     * */
    public static void showList(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println("");
    }
}

运行结果

19 95 9 17 1 8 
1 8 9 17 19 95 

Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值