排序算法 - 快速排序

2021-02-04 10:02:25 浏览数 (1)

代码语言:javascript复制
public class QuickSort {

    public static void quickSort(int[] arr, int l, int r){
        if(l >= r){
            return;
        }

        int p = partition(arr, l, r);
        quickSort(arr, l, p - 1);
        quickSort(arr, p   1, r);
    }

    public static int partition(int[] arr, int l, int r){
        int tmp = arr[l];

        int j = l;
        for(int i = l   1; i <= r; i  ){
            if(arr[i] < tmp){
                swap(arr,   j , i);
            }
        }

        swap(arr, l, j);
        return j;
    }

    private static void swap(int[] arr, int s, int d){
        int tmp = arr[s];
        arr[s] = arr[d];
        arr[d] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {2,4,5,3,1,8,1,4,3};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}

0 人点赞