java previous permutation
public static boolean prev_permutation(int[] arr) {
int len = arr.length;
int i = len - 1;
// 1. find largest i where arr[i - 1] > arr[i]
while (i > 0) {
if (arr[i - 1] > arr[i]) break;
i--;
}
if (i <= 0) return false;
// 2. find largest j where arr[i - 1] > arr[j] and j >= i
int j = len - 1;
while (j >= i) {
if (arr[i - 1] > arr[j]) break;
j--;
}
// 3. swap elements between arr[i-1] and arr[j]
swap(i - 1, j, arr);
// 4. reverse elements from i to end of array
len--;
while (i < len) {
swap(i, len, arr);
len--;
i++;
}
return true;
}
public static void swap(int x, int y, int[] arr) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
Also in Java:
- padding a string with 0 in java
- java string to boolean
- Enums injava
- java convert String to int
- android java convert double to 2 decimal places
- java iterator example
- java script num toSting syntax eror
- spring iterate
- java append to array
- how to remove all whitespace from string java
- store string elements in character array in java
- javafx textarea how to make smaller
- how to reverse a list in java
- java read string input
- fxmlloader getresource from another package
- java observable to observer stack overflow
- change java version command line debian
- get value textfield java
- islowercase java
- java null pointer exception
- entre clavier java
- HOW TO SUPRESS sonar warning in java code
- deleting elements of an array in java
- how to make an object move with arrow keys in java