aboutsummaryrefslogtreecommitdiff
path: root/collections/merge.go
blob: 31ffefd894676101faed16a809cb1d286e5050ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package collections

import "neonxp.ru/go/extra/utils"

// MergeScalar стабильное слияние двух слайсов скаляров
func MergeScalar[T utils.Scalar](s1, s2 []T) []T {
	i, j := 0, 0
	len1, len2 := len(s1), len(s2)
	result := make([]T, 0, len1+len2)
	for i < len1 && j < len2 {
		if s1[i] < s2[j] {
			result = append(result, s1[i])
			i++
			continue
		}
		result = append(result, s2[j])
		j++
	}
	result = append(result, s1[i:]...)
	result = append(result, s2[j:]...)
	return result
}

// Merge стабильное слияние двух слайсов
func Merge[T utils.Sortable[T]](s1, s2 []T) []T {
	i, j := 0, 0
	len1, len2 := len(s1), len(s2)
	result := make([]T, 0, len1+len2)
	for i < len1 && j < len2 {
		if s1[i].Less(s2[j]) {
			result = append(result, s1[i])
			i++
			continue
		}
		result = append(result, s2[j])
		j++
	}
	result = append(result, s1[i:]...)
	result = append(result, s2[j:]...)
	return result
}