Wednesday, February 21, 2018

Implementing Merge Sort in Golang

What is Merge Sort?
Merge Sort is sorting algorithm that using a divide and conquer algorithm.

Conceptually, a merge sort works as follows:
If the list is of length 0 or 1, then it is already sorted otherwise Divide the unsorted list into two sub-lists of about half the size. Sort each sub-lists recursively by re-applying the merge sort. Merge the two sub-lists back into one sorted list.


Time Complexity
In the best /average / worst case it gives a time complexity of  O(n log n)


Implementation

package main

import (
    "fmt"
)

func main() {
    var arrToBeSorted []int = []int{1,3,2,5,4,6,7,9,8,10}
    fmt.Println("\n --- unsorted --- \n\n", arrToBeSorted)
    fmt.Println("\n--- sorted ---\n\n", MergeSort(arrToBeSorted), "\n")
}

// Runs MergeSort algorithm
func MergeSort(input []int) []int {

    if len(input) < 2 {
        return input
    }
    mid := (len(input)) / 2
    return Merge(MergeSort(input[:mid]), MergeSort(input[mid:]))
}

// Merges left and right slice into newly created slice
func Merge(left, right []int) []int {

    size, i, j := len(left)+len(right), 0, 0
    input := make([]int, size, size)

    for k := 0; k < size; k++ {
        if i > len(left)-1 && j <= len(right)-1 {
            input[k] = right[j]
            j++
        } else if j > len(right)-1 && i <= len(left)-1 {
            input[k] = left[i]
            i++
        } else if left[i] < right[j] {
            input[k] = left[i]
            i++
        } else {
            input[k] = right[j]
            j++
        }
    }
    return input
}



Result:











Other Topics:






No comments:

Post a Comment