java prev 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:
- java print type of object
- how to detect if someone clicks on a jpanel in java
- loop java
- stack class in java
- java linked list functions
- java random integer
- java stream to list
- vertical traversal of binary tree
- make a commet in java
- how to check if a string contains only alphabets and space in java
- how to create a draw Rectangle in java
- loop while in java
- indexof java
- how to initialize main in java
- get first 5 characters of string java
- linux change java
- java string to boolean
- java nested loop
- remove item from arraylist in java
- how to get witdth of window android
- java loop hashmap
- java 8 findany on null list
- how to have a only number type in java
- Don't use a line-beased input after a token-based input.