Created
August 26, 2019 07:05
-
-
Save fukkong/198790b2828ee232ed1684f89540767a to your computer and use it in GitHub Desktop.
golang merge sort 2751
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 n int | |
_, _ = fmt.Scan(&n) | |
list := make([]int, n) | |
for i := 0; i < n; i++ { | |
_, _ = fmt.Scan(&list[i]) | |
} | |
fmt.Println(mergeSort(list)) | |
} | |
func merge(left []int, right []int) []int { | |
if len(left) == 0 { | |
return right | |
} | |
if len(right) == 0 { | |
return left | |
} | |
var sortedList []int | |
currentLeft := 0 | |
currentRight := 0 | |
for currentLeft < len(left) && currentRight < len(right) { | |
if left[currentLeft] <= right[currentRight] { | |
sortedList = append(sortedList, left[currentLeft]) | |
currentLeft += 1 | |
if currentLeft == len(left) { | |
sortedList = append(sortedList, right[currentRight:]...) | |
return sortedList | |
} | |
} else if left[currentLeft] > right[currentRight] { | |
sortedList = append(sortedList, right[currentRight]) | |
currentRight += 1 | |
if currentRight == len(right) { | |
sortedList = append(sortedList, left[currentLeft:]...) | |
return sortedList | |
} | |
} | |
} | |
return sortedList | |
} | |
func mergeSort(data []int) []int { | |
if len(data) <= 1 { | |
return data | |
} | |
mid := len(data) / 2 | |
left := mergeSort(data[:mid]) | |
right := mergeSort(data[mid:]) | |
return merge(left, right) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment