算法与数据结构-排序系列-快速排序(面试常问)

快速排序思想:从数组中选出一个基准值,将小于基准值的数放到基准值的左边,大于基准值的数组放到基准值的右边,然后从基准值处将数组分成两部分,用递归重复前面的操作,直到所有的数值有序。

实现方式:以下标为0的值为基准值,设置两个指针,一个指向待排序数组的首部,一个指向待排序数组的末尾,左指针由左向右扫描,找到所有比基准值大的值放到基准值的右边。右指针从右往左扫描,将小于基准值的数放到基准值左边,循环进行指导左指针和右指针重叠。然后从取到基准值的下标,将数组分成部分,对每一部分的数组重新执行前面的操作,直到所有数据有序。

代码如下

import java.util.Arrays;

public class QuickSort {

    public static int division(int[] base,int left,int right){
        int temp=0;
        int baseNum=base[left];
        while (left<right){
            while (left<right&&base[right]>=baseNum)right--;
            base[left]=base[right];
            while (left<right&&base[left]<=baseNum)left++;
            base[right]= base[left];

        }
        base[left]=baseNum;
        return left;
    }
    
    public static int[] sort(int[] base,int left,int right){
        if (left<right){
            int baseIndex=division(base,left,right);
            sort(base,left,baseIndex-1);
            sort(base,baseIndex+1,right);
        }
        return base;
    }

    public static void main(String[] args) throws InterruptedException {
        int[] base=new int[]{4,5,1,9,3,0,2};
        base=sort(base,0,base.length-1);
        Arrays.stream(base).forEach(k->System.out.print(k+","));
    }
}

猜你喜欢

转载自www.cnblogs.com/pianzhi/p/12368852.html