Next Permutation Java

To determine the lexicographically next permutation of a sequence of elements, apply the next permutation method. It refers to rearranging the items of an array into the following larger permutation in lexicographical order. Rearranging items to produce the lexicographically next permutation is the foundation of the next permutation algorithm.

The objective is to determine the next permutation in lexicographical order given an array of elements. In this section, we will discuss the two different approaches to implementing the next permutation algorithm in Java: using built-in functions and by using new swap and reverse functions.

Steps to Find the Next Permutation

1. Choose the first component to switch

Locate the first element in the array (nums[i]), starting from the right end that is smaller than the next element (nums[i + 1]).

2. Identify the smallest element to the right

Find the lowest element to the right of nums[i] that is greater than nums[i] by scanning the array once again from the right if such an element, nums[i], is found.

3. Change the two components

Replace nums[i] with the element that was identified, making sure that the new arrangement is larger than the previous one.

4. Turn the subarray around to the right

To the right of the original element (nums[i]), reverse the subarray. By ensuring that the remainder of the array is arranged in ascending order, this step yields the smallest lexicographically next permutation.

Approach 1: Using swap() and reverse() Function

Let's start by noting that the current permutation is modified to be lexicographically greater, which leads to the next permutation.

  • Locate the pivot by finding the longest non-increasing suffix.
  • If the suffix comprises the full array, a higher-order permutation cannot exist.
  • Traverse from the end to find the pivot's rightmost successor.
  • Change the pivot and the heir.
  • To guarantee an increasing order, reverse the suffix.

NextPermutation.java

Output:

[100, 300, 200]

Method 2: By Using Built-in Functions

NextPermutationBuiltIn.java

Output:

[10, 30, 20]

Conclusion

Conclusively, comprehending and applying the Next Permutation algorithm in Java offers significant perspectives into algorithmic reasoning and array management. To generate the next lexicographically bigger permutation, the objective is to find an accurate and optimal solution, whether using built-in algorithms or bespoke functions.






Latest Courses