diff options
author | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2022-05-01 21:50:12 +0300 |
---|---|---|
committer | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2022-05-01 21:50:12 +0300 |
commit | 9fcf8e29214210612d545bed50d7f889800ac639 (patch) | |
tree | 3a99d2cd37fb8158d49abc1de6298758d205c9dd /collections/merge.go |
Initial
Diffstat (limited to 'collections/merge.go')
-rw-r--r-- | collections/merge.go | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/collections/merge.go b/collections/merge.go new file mode 100644 index 0000000..6fcf875 --- /dev/null +++ b/collections/merge.go @@ -0,0 +1,41 @@ +package collections + +import "go.neonxp.dev/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 +} |