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:
How to build NGINX RTMP module, Setup Live Streaming with NGINX RTMP module, Publishing Stream with Open Broadcaster Software (OBS), Create Adaptive Streaming with NGINX RTMP, Implementing Filtergraph in Streaming with NGINX RTMP, How to Implement Running Text in Streaming with NGINX RTMP, How to build OpenSceneGraph with Code::Blocks, How to build OpenSceneGraph with Visual Studio 2010, Building Geometry Model, How to run OpenSceneGraph with Netbean IDE 8.2 C++, Rendering Basic Shapes, Using OSG Node to Load 3D Object Model, Rendering 3D Simulator with OpenSceneGraph, How to compile wxWidgets with Visual Studio 2010, How to Setup Debugging in Golang with Visual Code
No comments:
Post a Comment