Created
December 1, 2022 02:29
-
-
Save xeoncross/8fd8f4a497951d1e6ddd9578de6a9342 to your computer and use it in GitHub Desktop.
Generics merge sort for ordered slices ([]int) inplace (WIP)
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
package mergesort | |
import ( | |
"fmt" | |
"testing" | |
"golang.org/x/exp/constraints" | |
) | |
// based on https://github.com/TheAlgorithms/Go/blob/master/sort/mergesort.go | |
// Merge Perform merge sort on a slice | |
func Merge[T constraints.Ordered](items []T, left, right int) { | |
if (right - left) < 2 { | |
return | |
} | |
var middle = left + (right-left)/2 | |
Merge(items, left, middle) | |
Merge(items, middle, right) | |
merge(items, left, middle, right) | |
} | |
func merge[T constraints.Ordered](a []T, left, middle, right int) { | |
var i = left // left - middle | |
var j = middle // middle - right | |
for i < middle && j < right { | |
if a[i] <= a[j] { | |
i++ | |
} else { | |
a[i], a[j] = a[j], a[i] // swap | |
j++ | |
} | |
} | |
for i < middle { | |
a[i], a[j] = a[j], a[i] // swap | |
i++ | |
j++ | |
} | |
for j < right { | |
a[i], a[j] = a[j], a[i] // swap | |
i++ | |
j++ | |
} | |
} | |
func TestMerge(t *testing.T) { | |
v := []int{3, 2, 1, 5, 4} | |
fmt.Println(v) | |
Merge(v, 0, len(v)) | |
fmt.Println(v) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment