Algorithms and Data Structures - Selection Sort

Understand Selection Sort, which repeatedly finds the minimum element and swaps it into position. Covers O(n²) time complexity and a Go implementation.

Read in: ja
Algorithms and Data Structures - Selection Sort

Overview

Learn algorithms and data structures with reference to Algorithm Encyclopedia.

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

Selection Sort

Time Complexity

Implementation

package main

func selectionSort(n []int) []int {
	for i := 0; i < len(n); i++ {
		min := i

		// Compare the smallest value in the data with the first value
		for j := i + 1; j < len(n); j++ {
			if n[j] < n[min] {
				min = j
			}
		}

		// Swap
		n[i], n[min] = n[min], n[i]
	}

	return n
}

func main() {
	n := []int{2, 1, 5, 7, 9}
	fmt.Println(selectionSort(n))
}

References

Tags: Selection 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