Created
September 30, 2021 05:21
-
-
Save caryyu/cb71b850574e8ddf47c4b20ab1b0242c to your computer and use it in GitHub Desktop.
Algorithm of mergesort
This file contains hidden or 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 main | |
import "fmt" | |
func main() { | |
var nums []int = []int{10, 7, 8, 1, 4, 3} | |
topDownMergesort(nums) | |
fmt.Println(nums) | |
} | |
func topDownMergesort(a []int) { | |
var b []int = make([]int, len(a)) | |
copy(b, a) | |
topDownSplitMerge(b, 0, len(b), a) | |
} | |
func topDownSplitMerge(b []int, idx1 int, idx2 int, a []int) { | |
if idx2-idx1 <= 1 { | |
return | |
} | |
var middle int = (idx2 + idx1) / 2 | |
topDownSplitMerge(a, idx1, middle, b) | |
topDownSplitMerge(a, middle, idx2, b) | |
topDownMerge(b, idx1, middle, idx2, a) | |
} | |
func topDownMerge(a []int, idx1 int, middle int, idx2 int, b []int) { | |
i := idx1 | |
j := middle | |
for k := idx1; k < idx2; k++ { | |
if i < middle && (j >= idx2 || a[i] <= b[j]) { | |
b[k] = a[i] | |
i++ | |
} else { | |
b[k] = a[j] | |
j++ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation_using_lists