|
| 1 | +package main |
| 2 | + |
| 3 | +import "fmt" |
| 4 | + |
| 5 | +func mergeSort(a []int) []int { |
| 6 | + |
| 7 | + if len(a) <= 1 { |
| 8 | + return a |
| 9 | + } |
| 10 | + |
| 11 | + left := make([]int, 0) |
| 12 | + right := make([]int, 0) |
| 13 | + m := len(a) / 2 |
| 14 | + |
| 15 | + for i, x := range a { |
| 16 | + switch { |
| 17 | + case i < m: |
| 18 | + left = append(left, x) |
| 19 | + case i >= m: |
| 20 | + right = append(right, x) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + left = mergeSort(left) |
| 25 | + right = mergeSort(right) |
| 26 | + |
| 27 | + return merge(left, right) |
| 28 | +} |
| 29 | + |
| 30 | +func merge(left, right []int) []int { |
| 31 | + |
| 32 | + results := make([]int, 0) |
| 33 | + |
| 34 | + for len(left) > 0 || len(right) > 0 { |
| 35 | + if len(left) > 0 && len(right) > 0 { |
| 36 | + if left[0] <= right[0] { |
| 37 | + results = append(results, left[0]) |
| 38 | + left = left[1:len(left)] |
| 39 | + } else { |
| 40 | + results = append(results, right[0]) |
| 41 | + right = right[1:len(right)] |
| 42 | + } |
| 43 | + } else if len(left) > 0 { |
| 44 | + results = append(results, left[0]) |
| 45 | + left = left[1:len(left)] |
| 46 | + } else if len(right) > 0 { |
| 47 | + results = append(results, right[0]) |
| 48 | + right = right[1:len(right)] |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return results |
| 53 | +} |
| 54 | + |
| 55 | +func main() { |
| 56 | + |
| 57 | + arrayzor := []int{1, 6, 2, 4, 9, 0, 5, 3, 7, 8} |
| 58 | + fmt.Println("Unsorted array: ", arrayzor) |
| 59 | + arrayzor = mergeSort(arrayzor) |
| 60 | + fmt.Println("Sorted array: ", arrayzor) |
| 61 | +} |
0 commit comments