Array full array (recursive)-Java

Assuming that there are 6 numbers in full arrangement (1, 2, 3, 4, 5, 6),
then there must be the following six situations
=> 1,2,3,4,5,6
=> 2,1,3,4,5,6
=> 3,2,1,4,5,6
=> 4,2,3,1,5,6
=> 5,2,3,4,1,6
=> 6,2,3,4,5,1
Then the selected part is fully arranged.
That is to say, every number that appears in this set of data must appear once as the beginning.
According to this principle, a recursive algorithm can be written to realize the complete arrangement of the array.

public static void main(String[] args) {
    
    
	int A[] = new int[]{
    
    1, 2, 3};
    perm(A, 0);
}

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

public static void printArray(int A[], int n) {
    
    
    for (int i : A) {
    
    
        System.out.print(i + " ");
    }
    System.out.println();
}

public static void perm(int A[], int p) {
    
    
    if (p == A.length) {
    
    
        printArray(A, A.length - 1);
    } else {
    
    
        for (int i = p; i < A.length; i++) {
    
    
            swap(A, i, p);
            perm(A, p + 1);
            swap(A, i, p);
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_46390568/article/details/107552223