MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / NextPermutation

Function NextPermutation

math/permutation/next_permutation.go:10–39  ·  view source on GitHub ↗
(nums []int)

Source from the content-addressed store, hash-verified

8package permutation
9
10func NextPermutation(nums []int) {
11 pivot := 0
12 for pivot = len(nums) - 2; pivot >= 0; pivot-- {
13 if nums[pivot] < nums[pivot+1] {
14 break
15 }
16 }
17 if pivot < 0 {
18 // current permutation is the last and must be reversed totally
19 for l, r := 0, len(nums)-1; l < r; l, r = l+1, r-1 {
20 nums[l], nums[r] = nums[r], nums[l]
21 }
22 } else {
23 succ := 0
24 for succ = len(nums) - 1; succ > pivot; succ = succ - 1 {
25 if nums[succ] > nums[pivot] {
26 break
27 }
28 }
29
30 // Swap the pivot and successor
31 nums[pivot], nums[succ] = nums[succ], nums[pivot]
32
33 // Reverse the suffix part to minimize it
34 for l, r := pivot+1, len(nums)-1; l < r; l, r = l+1, r-1 {
35 nums[l], nums[r] = nums[r], nums[l]
36 }
37 }
38
39}

Callers 1

TestNextPermutationFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestNextPermutationFunction · 0.68