Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently find the next greater permutation of a list of values, in Java?

/*
	This is an implementation that demonstrates
	how to efficiently find the next greater
	permutation for a list of values.
	For example, next greater permutation for:
	- [1, 2, 3] -> [1, 3, 2]
	- [2, 3, 1] -> [3, 1, 2]

	Let n be the number of values in the list.

	Time complexity: O(n) 
	Space complexity: O(1)
*/
import java.util.Arrays;

public class NextGreaterPermutation {
	public static void main(String[] args) {
		int[] nums = { 1, 2, 3 };
		nextPermutation(nums);
		System.out.println(Arrays.toString(nums)); // [1, 3, 2]
		nums = new int[] { 2, 3, 1 };
		nextPermutation(nums);
		System.out.println(Arrays.toString(nums)); // [3, 1, 2]
	}

	public static void nextPermutation(int[] nums) {
		int i = -1;
		// Find position of rightmost value
		// that is smaller than its successor
		for (int j = nums.length - 2; j >= 0; j--) {
			if (nums[j] < nums[j + 1]) {
				i = j;
				break;
			}
		}
		if (i == -1) {
			// This is the max combination
			// We need to sort it in ascending order
			reverse(nums, 0);
			return;
		}
		// Find rightmost value greater than the one
		// at index i and swap it with the one at i
		for (int j = nums.length - 1; j > i; j--) {
			if (nums[j] > nums[i]) {
				swap(nums, i, j);
				break;
			}
		}
		// Reverse the elements to the right of i
		reverse(nums, i + 1);
	}

	private static void reverse(int[] nums, int start) {
		int i = start, j = nums.length - 1;
		while (i < j) {
			swap(nums, i, j);
			i++;
			j--;
		}
	}

	private static void swap(int[] nums, int i, int j) {
		int temp = nums[i];
		nums[i] = nums[j];
		nums[j] = temp;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: timestamp to date java 
Java :: get the image from camera click in android 
Java :: how to assert that an exception is thrown java 
Java :: java comments 
Java :: integer to string java 
Java :: array java 
Java :: logical operators in java 
Java :: ternary operator in java for null check 
Java :: Add delay to code in Android 
Java :: c# or java 
Java :: abstract class in java 
Java :: Spring boot enable openapi swagger accessed 
Java :: spring boot base url 
Java :: set image programmatically android 
Java :: hide element selenium 
Java :: enum set in java 
Java :: javac clear 
Java :: connect sqlite for java 
Java :: Java How to use Set? 
Java :: find length of array java 
Java :: Using enum values as string literals 
Java :: java swing dialog box 
Java :: how to delete character in string java 
Java :: simple function java 
Java :: java substring after last char 
Java :: java suppresswarnings unchecked 
Java :: linkedhashmap in java 
Java :: java toggle button get state 
Java :: what is maven artifact 
Java :: android ecode base64 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =