Algorithms and Data Structures - Merge Sort

Learn Merge Sort, a divide-and-conquer sorting algorithm with O(n log n) worst-case time complexity. Covers recursive splitting, merging steps, and a Go implementation.

Read in: ja
Algorithms and Data Structures - Merge Sort

Overview

Learning algorithms and data structures with reference to Algorithm Encyclopedia.

The implementation is also available at github - bmf-san/road-to-algorithm-master.

Merge Sort

Time Complexity

Implementation

// cf. https://github.com/TheAlgorithms/Go/blob/master/sorts/merge_sort.go
package main

func merge(a []int, b []int) []int {
	r := make([]int, len(a)+len(b))
	i := 0
	j := 0

	for i < len(a) && j < len(b) {
		if a[i] <= b[j] {
			r[i+j] = a[i]
			i++
		} else {
			r[i+j] = b[j]
			j++
		}
	}

	for i < len(a) {
		r[i+j] = a[i]
		i++
	}

	for j < len(b) {
		r[i+j] = b[j]
		j++
	}

	return r
}

func mergeSort(n []int) []int {
	if len(n) < 2 {
		return n
	}

	var middle = len(n) / 2
	a := mergeSort(n[:middle])
	b := mergeSort(n[middle:])
	return merge(a, b)
}

References

Tags: Merge Sort
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles