Skip to content

Instantly share code, notes, and snippets.

@phaniram
Created January 5, 2012 02:24
Show Gist options
  • Save phaniram/1563390 to your computer and use it in GitHub Desktop.
Save phaniram/1563390 to your computer and use it in GitHub Desktop.
Unique Permutations of an int[]
public class Permutations {
public static boolean permuteLexically(int[] data) {
int k = data.length - 2;
while (data[k] >= data[k + 1]) {
k--;
if (k < 0) {
return false;
}
}
int l = data.length - 1;
while (data[k] >= data[l]) {
l--;
}
swap(data, k, l);
int length = data.length - (k + 1);
for (int i = 0; i < length / 2; i++) {
swap(data, k + 1 + i, data.length - i - 1);
}
return true;
}
private static void swap(int[] data, int k, int l) {
data[k]=data[k]+data[l];
data[l]=data[k]-data[l];
data[k]=data[k]-data[l];
}
public static void main(String[] args) {
int[] data = { 1,2,3 };
Arrays.sort(data);
do {
System.err.println(Arrays.toString(data));
} while(Util.permuteLexically(data));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment