Last active
September 14, 2017 15:31
-
-
Save irtaylor/17654e5f16650eeb37370402f25fdf55 to your computer and use it in GitHub Desktop.
merge sort in go
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
// Merge Sort Go, Ian Taylor 2017 | |
// A very simple mergesort implementation, emphasizing algorithmic clarity over optimization | |
package main | |
import ( | |
"fmt" | |
) | |
// sort an unsorted array in ascending order | |
func mergeSort(A []int) []int { | |
if len(A) <= 1 { | |
return A | |
} else { | |
A = merge(mergeSort(A[:len(A)/2]), mergeSort(A[len(A)/2:])) | |
} | |
return A | |
} | |
// merge two ordered arrays, return an ordered array | |
func merge(A []int, B []int) []int { | |
size := len(A) + len(B) | |
C := make([]int, size, size) | |
for i, j, k := 0, 0 ,0; k < size; k += 1 { | |
// check indices of A and B for out of bounds | |
if i >= len(A) { | |
copy(C[k:], B[j:]) | |
return C | |
} else if j >= len(B) { | |
copy(C[k:], A[i:]) | |
return C | |
} | |
// make the comparison and merge | |
if A[i] < B[j] { | |
C[k] = A[i] | |
i += 1 | |
} else { | |
C[k] = B[j] | |
j += 1 | |
} | |
} | |
return C | |
} | |
func main() { | |
a := []int{1, 4, 7, 9, 14} | |
b := []int{2, 3, 10, 12, 18, 22, 33} | |
fmt.Println("a: ", a) | |
fmt.Println("b: ", b) | |
fmt.Println("merge: ", merge(a, b), "\n") | |
c := []int{13, 48, 1, 4, -4, -3, 20, 0, 0, 100, 99, 11, 3, 7} | |
fmt.Println("unsorted: ", c) | |
fmt.Println("mergeSort: ", mergeSort(c)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment