简体   繁体   中英

Java Program to Show the Permutations of an Integer Array

Trying to show the permutations of an int array using recursion, however for some reason it doesn't print anything when I call the function. Is there something in the main function I'm missing?

     public static void Permutation(int[] a, int prefix) {

    int length = a.length;

    if (length == prefix) {

        printArray(a);

    }

    else {

        for (int i = 0; i < prefix; i++) {

            swap(a, prefix, i);

            Permutation(a, prefix + 1);

            swap(a, prefix, i);

        }
    }
}

public static void swap(int[] a, int x, int y) {

    int z = a[x];

    a[x] = a[y];

    a[y] = z;

}

public static void printArray(int[] thing) {

    System.out.println("\n");

    for (int x = 0; x < thing.length; x++)
        System.out.print(thing[x]);

}

public static void main(String[] args) {

    int a[] = { 1, 2, 3 };
            Permutation(a, 0);
    }

Say I have an int array of 1, 2, and 3. The output should be

1 2 3
1 3 2 
2 1 3 
2 3 1
3 1 2 
3 2 1

看看你的for循环并分析程序:)

for (int i = 0; i < prefix; i++) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM