Implementing next_permutation() in Java with Examples

Given an array or string, the task is to find the next lexicographically greater permutation of it in Java.

Examples:

Input: string = "gfg"
Output: ggf

Input: arr[] = {1, 2, 3}
Output: {1, 3, 2}

In C++, there is a specific function that saves us from a lot of code. It’s in the header file #include<algorithm>. The function is next_permutation(a.begin(), a.end()). It is used to rearrange the elements in the range [first, last) into the next lexicographically greater permutation. A permutation is each one of the N! possible arrangements the elements can take (where N is the number of elements in the range). Different permutations can be ordered according to how they compare lexicographically to each other.



Apparently, Java does not provide any such inbuilt method. Therefore, this article discusses how to implement the next permutation function in Java along with its algorithm.

Algorithm:

  1. Find the longest non-increasing suffix and find the pivot.
  2. If the suffix is the whole array, then there is no higher order permutation for the data.
  3. Find the rightmost successor to the pivot.
  4. Swap the successor and the pivot.
  5. Reverse the suffix.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the next_permutation method
  
import java.util.Arrays;
  
public class nextPermutation {
  
    // Function to swap the data
    // present in the left and right indices
    public static int[] swap(int data[], int left, int right)
    {
  
        // Swap the data
        int temp = data[left];
        data[left] = data[right];
        data[right] = temp;
  
        // Return the updated array
        return data;
    }
  
    // Function to reverse the sub-array
    // starting from left to the right
    // both inclusive
    public static int[] reverse(int data[], int left, int right)
    {
  
        // Reverse the sub-array
        while (left < right) {
            int temp = data[left];
            data[left++] = data[right];
            data[right--] = temp;
        }
  
        // Return the updated array
        return data;
    }
  
    // Function to find the next permutation
    // of the given integer array
    public static boolean findNextPermutation(int data[])
    {
  
        // If the given dataset is empty
        // or contains only one element
        // next_permutation is not possible
        if (data.length <= 1)
            return false;
  
        int last = data.length - 2;
  
        // find the longest non-increasing suffix
        // and find the pivot
        while (last >= 0) {
            if (data[last] < data[last + 1]) {
                break;
            }
            last--;
        }
  
        // If there is no increasing pair
        // there is no higher order permutation
        if (last < 0)
            return false;
  
        int nextGreater = data.length - 1;
  
        // Find the rightmost successor to the pivot
        for (int i = data.length - 1; i > last; i--) {
            if (data[i] > data[last]) {
                nextGreater = i;
                break;
            }
        }
  
        // Swap the successor and the pivot
        data = swap(data, nextGreater, last);
  
        // Reverse the suffix
        data = reverse(data, last + 1, data.length - 1);
  
        // Return true as the next_permutation is done
        return true;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        int data[] = { 1, 2, 3 };
        if (!findNextPermutation(data))
            System.out.println("There is no higher"
                               + " order permutation "
                               + "for the given data.");
        else {
            System.out.println(Arrays.toString(data));
        }
    }
}

chevron_right


Output:

[1, 3, 2]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.