快速排序

上代码,加注释,直接运行,多debug

import java.util.*;

public class QuickSort {

    public static void main(String[] args) throws Exception {
        int[] sourceArray = new int[]{2,4,234,8,2,5,7,92,4,534,45};
    }

    private static int[] sort(int[] sourceArray) throws Exception {
        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
        return quickSort(arr, 0, arr.length - 1);
    }

    private static int[] quickSort(int[] arr, int left, int right) {
        //打印每次排序结果
        System.out.println(Arrays.toString(arr));
        if (left < right) {
            int partitionIndex = partition(arr, left, right);
            quickSort(arr, left, partitionIndex - 1);
            quickSort(arr, partitionIndex + 1, right);
        }
        return arr;
    }
    
    //注意交换分两种
    //1、将小于基准值的数据移动到右边
    //2、将基准值移动到中间
    //3、导致基准值右边或左边不是有序的,最终有序是多次排序的结果
    private static int partition(int[] arr, int left, int right) {
        // 设定基准值(pivot)
        int pivot = left;
        int index = pivot + 1;
        for (int i = index; i <= right; i++) {
            if (arr[i] < arr[pivot]) {
                swap(arr, i, index);
                index++;
            }
        }
        swap(arr, pivot, index - 1);
        return index - 1;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

 

posted @ 2020-08-11 09:47  瓶子老大  阅读(190)  评论(0编辑  收藏  举报