Skip to content

Instantly share code, notes, and snippets.

@istepura
Last active July 14, 2017 17:59
Show Gist options
  • Select an option

  • Save istepura/9222616 to your computer and use it in GitHub Desktop.

Select an option

Save istepura/9222616 to your computer and use it in GitHub Desktop.
Generating permutations of arr in lexicographic order in C#
public IEnumerable<int[]> Permut(int[] arr){
while (true){
yield return arr;
var j = arr.Length - 2;
while (j >= 0 && arr[j] >= arr[j+1]) j--;
if (j < 0) break;
var l = arr.Length -1;
while (arr[j] >= arr[l]) l--;
var tmp = arr[l]; arr[l] = arr[j]; arr[j] = tmp;
var k = j +1;
l = arr.Length -1;
while (k < l){
var t = arr[k];
arr[k] = arr[l];
arr[l] = t;
k++;
l--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment