手写快速排序算法——QuickSort(Java代码实现)

3 篇文章 0 订阅

QuickSort

/**
 * @program: JavaTest
 * @description: 快速排序实现
 * @author: yanghaoran
 * @create: 2019-05-26 12:17
 **/
public class QuickSort {
    static int[] a = {4, 5, 7, 1, 9, 8, 3, 2, 6};
    // 结果集数组
    int[] result = new int[a.length];
    public static void main(String[] args) {
        QuickSort qS = new QuickSort();
        qS.result = qS.quickSort(a);
        // 遍历展示
        for (int i = 0; i < qS.result.length; i++) {
            System.out.print(qS.result[i] + " ");
        }
    }

    public int[] quickSort (int[] b) {
        // 左指针
        int left = 0;
        // 右指针
        int right = b.length - 2;
        // 自我选定预轴心(几乎可以随意选择看自己数组内容恰当选择)
        int pivot = b.length - 1;
        // 左指针右移
        for (int i = 1; b[left] <= b[pivot] && i <= b.length - 1; i++) {
            left = i;
        }
        // 右指针左移
        for (int i = b.length - 1; b[right] >= b[pivot] && i >= 0; i--) {
            right = i;
        }
        // 左右指针相撞找到目标轴心
        if (left == right || left == right + 1) {
            int temp = b[left];
            b[left] = b[pivot];
            b[pivot] = temp;
            // 以轴心为轴分割为两个数组
            int[] tempArray1 = new int[left];
            int[] tempArray2 = new int[b.length - right - 2];
            for (int i = 0; i < left; i++) {
                tempArray1[i] = b[i];
            }
            for (int i = 0; i < right - 1; i++) {
                tempArray2[i] = b[i + left + 1];
            }
            // 递归结束条件(长度1或者2都为结束因为顺序会被排好)
            if (tempArray1.length == 1 || tempArray1.length == 2) {
                return tempArray1;
            } else {
                tempArray1 = quickSort(tempArray1);
                // 递归出来后对原数组进行恢复
                for (int i = 0; i < left; i++) {
                     b[i] = tempArray1[i];
                }
            }
            // 递归结束条件(长度1或者2都为结束因为顺序会被排好)
            if (tempArray2.length == 1 || tempArray2.length == 2) {
                return tempArray2;
            } else {
                tempArray2 = quickSort(tempArray2);
                // 递归出来后对原数组进行恢复
                for (int i = 0; i < right - 1; i++) {
                    b[i + left + 1] = tempArray2[i];
                }
            }
            // 左右指针未相撞,交换左右指针内容继续递归左右指针的平移
        } else {
            int temp = b[left];
            b[left] = b[right];
            b[right] = temp;
            quickSort(b);
        }
        return b;
    }
}

自己因为之前对快速排序长时间不用就已经忘记了,特意重新写了一遍追加记忆,如有不明白即可交流~
**如果对快速排序原理有疑问可以先看视频~**https://www.bilibili.com/video/av39093184?t=199
也可评论交流其他排序算法~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值