MCPcopy Create free account
hub / github.com/arnauddri/algorithms / recursiveCount

Function recursiveCount

algorithms/maths/permutations-count/permutations.go:5–44  ·  view source on GitHub ↗
(a []int)

Source from the content-addressed store, hash-verified

3import ()
4
5func recursiveCount(a []int) ([]int, int) {
6 n := len(a)
7 if n < 2 {
8 return a, 0
9 }
10
11 b, left := recursiveCount(a[:n>>1])
12 c, right := recursiveCount(a[n>>1:])
13 d := make([]int, 0)
14
15 i, j := 0, 0
16 inversions := 0
17
18 for k := 0; k < n; k++ {
19 if b[i] < c[j] {
20 d = append(d, b[i])
21 i++
22 if i == len(b) {
23 for j < len(c) {
24 d = append(d, c[j])
25 j++
26 }
27 break
28 }
29 } else {
30 d = append(d, c[j])
31 j++
32 inversions += len(b) - i
33 if j == len(c) {
34 for i < len(b) {
35 d = append(d, b[i])
36 i++
37 }
38 break
39 }
40 }
41 }
42
43 return d, left + right + inversions
44}
45
46func iterativeCount(array []int) int {
47 n := len(array)

Callers 2

TestRecursiveFunction · 0.85
BenchmarkRecursiveFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestRecursiveFunction · 0.68
BenchmarkRecursiveFunction · 0.68