1

I am trying to return the permutations of an integer in descending order. Currently I have code which returns all the permutations of a number however, it is not in descending order. I am unsure to whether I should use an array instead and it may be easier. My current code is:

// Function to print all the permutations of str
static void printPermutn(String str, String ans)
{
    // If string is empty
    if (str.length() == 0) {
        System.out.print(ans + " ");
        return;
    }

    for (int i = 0; i < str.length(); i++) {

        // 1st character of str
        char ch = str.charAt(i);

        // Rest of the string after excluding
        // the 1st character
        String ros = str.substring(0, i) +
                str.substring(i + 1);

        // Recurvise call

        printPermutn(ros, ans + ch);
    }
}
1

1 Answer 1

1

You can use global List<String> permutations then put all values into this collection
Finally, you can sort it in a descending order using
Collections.sort(permutations, Collections.reverseOrder());

private static List<String> permutations;

public static void main(String[] args) {
    permutations = new ArrayList<>();
    printPermutn("123", "");

    System.out.println();
    System.out.println("permutations BEFORE sorting");
    System.out.println(permutations);

    // sort
    Collections.sort(permutations, Collections.reverseOrder());

    System.out.println("permutations AFTER sorting");
    System.out.println(permutations);
}

// Function to print all the permutations of str
static void printPermutn(String str, String ans) {
    // If string is empty
    if (str.length() == 0) {
        System.out.print(ans + " ");
        permutations.add(ans);
        return;
    }

    for (int i = 0; i < str.length(); i++) {

        // 1st character of str
        char ch = str.charAt(i);

        // Rest of the string after excluding
        // the 1st character
        String ros = str.substring(0, i) + str.substring(i + 1);

        // Recurvise call

        printPermutn(ros, ans + ch);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.