17.快速排序

文章目录

1.分析

在这里插入图片描述

2.代码

package com.atguigu.sort;

import java.util.Arrays;

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {-9,78,0,23,-567,70};
        quickSort(arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));

    }

    public static void quickSort(int[] arr,int left, int right){
        int l = left;// 左索引
        int r = right; // 右索引
        int pivot = arr[(left+right)/2];
        int temp = 0;
        // 循环目的:让比pivot小的值放到左边,大的值放到右边
        while (l < r){

            // 在pivot的左边一直找,找到大于等于pivot的值,退出循环
            while (arr[l] < pivot){
                l += 1;
            }
            // 在pivot的右边一直找,找到小于等于pivot的值,退出循环
            while (arr[l] > pivot){
                r -= 1;
            }

            // 如果 l>=r 说明pivot的左右两边的值,已经是左边全部小于等于pivot,右边大于等于pivot
            if (l >= r){
                break;
            }

            // 交换
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;

            // 如果交换完后,发现arr[l] == pivot ,r向前移一步
            if (arr[l] == pivot){
                r -= 1;
            }
            // 如果交换完后,发现arr[r] == pivot ,l向后移一步
            if (arr[r] == pivot){
                l += 1;
            }

        }

        // 如果 l==r,必须l++,r--,否则出现栈溢出
        if (l == r) {
            l += 1;
            r -= 1;
        }
        // 向左递归
        if (left < r){
            quickSort(arr,left,r);
        }
        // 向右递归
        if (right > l){
            quickSort(arr,l,right);
        }
    }
}