📜  java 程序中的快速排序 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:06.951000             🧑  作者: Mango

代码示例1
package quickSort;

import java.util.Arrays;

public class Main {

    private int[] A;

    public int[] getA() {
        return A;
    }

    public void setA(int[] a) {
        A = a;
    }

    public static void main(String[] args) {
        Main a = new Main();
        int[] A = {2, 1, 9, 7, 4, 8, 10, 5, 6, 3};
        a.setA(A);
        a.quickSort(0, A.length-1);
        System.out.println(Arrays.toString(a.getA()));
    }

    public void quickSort(int l, int r){
        if(l < r){System.out.println(Arrays.toString(getA()));
            int m = partition(l, r);
            System.out.println(getA()[m]);
            quickSort(l, m-1);System.out.println(Arrays.toString(getA()));
            quickSort(m+1, r);System.out.println(Arrays.toString(getA()));

        }
    }

    public int partition(int l, int r) {
        int pivot = getA()[r];
        int i = l;
        for(int j = l; j < r; j++){
            if(getA()[j] <= pivot){
                swap(i, j);
                i++;
            }
        }
        swap(i, r);
        return i;
    }

    public void swap(int i, int r){
        int[] A = getA();
        int lel = A[i];
        A[i] = A[r];
        A[r] = lel;
        setA(A);
    }
}