Skip to content

Commit

Permalink
merge: add merge sort (#456)
Browse files Browse the repository at this point in the history
* add merge sort

* change code style

* move iterative implementation  to mergesort.go

* fix: rename MegrgeSortIter to MergeIter

Co-authored-by: zhaodeliang <[email protected]>
Co-authored-by: Rak Laptudirm <[email protected]>
  • Loading branch information
3 people authored Jan 4, 2022
1 parent a918456 commit 6134d6e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions sort/mergesort.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package sort

import "github.com/TheAlgorithms/Go/math/min"

func merge(a []int, b []int) []int {

var r = make([]int, len(a)+len(b))
Expand Down Expand Up @@ -45,3 +47,13 @@ func Mergesort(items []int) []int {
return merge(a, b)

}

func MergeIter(items []int) []int {
for step := 1; step < len(items); step += step {
for i := 0; i+step < len(items); i += 2 * step {
tmp := merge(items[i:i+step], items[i+step:min.Int(i+2*step, len(items))])
copy(items[i:], tmp)
}
}
return items
}
8 changes: 8 additions & 0 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ func TestMerge(t *testing.T) {
testFramework(t, Mergesort)
}

func TestMergeIter(t *testing.T) {
testFramework(t, MergeIter)
}

func TestHeap(t *testing.T) {
testFramework(t, HeapSort)
}
Expand Down Expand Up @@ -187,6 +191,10 @@ func BenchmarkMerge(b *testing.B) {
benchmarkFramework(b, Mergesort)
}

func BenchmarkMergeIter(b *testing.B) {
benchmarkFramework(b, MergeIter)
}

func BenchmarkHeap(b *testing.B) {
benchmarkFramework(b, HeapSort)
}
Expand Down

0 comments on commit 6134d6e

Please sign in to comment.