Skip to content

Instantly share code, notes, and snippets.

@ex-hota911
Last active October 14, 2017 06:29
Show Gist options
  • Select an option

  • Save ex-hota911/69e539cc966fd573aa449be0e99a2a95 to your computer and use it in GitHub Desktop.

Select an option

Save ex-hota911/69e539cc966fd573aa449be0e99a2a95 to your computer and use it in GitHub Desktop.
next permutation for Java List.
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Permutations {
/**
* Rearrange the list into the next lexicographically greater permutation if exists.
*
* @return true if such a permutation exists, otherwise false.
*/
public static <T extends Comparable> boolean nextPermutation(List<T> list) {
return nextPermutation(list, (a, b) -> a.compareTo(b));
}
/**
* Rearrange the list into the next lexicographically greater permutation if exists.
*
* @return true if such a permutation exists, otherwise false.
*/
public static <T> boolean nextPermutation(List<T> list, Comparator<T> comparator) {
// Find the biggest i which meets list[i] < list[i + 1]
int i = list.size() - 2;
for (; i >= 0; i--) {
T next = list.get(i + 1);
T tmp = list.get(i);
if (comparator.compare(tmp, next) < 0) {
break;
}
}
if (i < 0) {
return false;
}
T pivot = list.get(i);
// Find the biggest j where list[j - 1] > list[i].
int j = i + 2;
for (; j < list.size(); j++) {
if (comparator.compare(list.get(j), pivot) <= 0) break;
}
Collections.swap(list, i, j - 1);
Collections.reverse(list.subList(i + 1, list.size()));
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment