Last active
January 15, 2017 05:47
-
-
Save robot-dreams/151da6a6a6a4febae77a6b09a20a29a5 to your computer and use it in GitHub Desktop.
Next lexicographic permutation (iterative)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func nextPermutation(a []int) { | |
// Find the greatest index i such that a[i] < a[i + 1] | |
i := len(a) - 2 | |
for i >= 0 && a[i] >= a[i+1] { | |
i-- | |
} | |
if i >= 0 { | |
// Find the greatest index j > i such that a[i] < a[j]; such an index | |
// exists because a[i] < a[i + 1] | |
j := len(a) - 1 | |
for a[i] >= a[j] { | |
j-- | |
} | |
a[i], a[j] = a[j], a[i] | |
} | |
reverse(a[i+1:]) | |
} | |
func reverse(a []int) { | |
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { | |
a[i], a[j] = a[j], a[i] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment