Golang Selection Sort Algorithm

Selection sort is an algorithm that divides the input collection into two fragments. This sublist of elements is sorted by swapping the smallest or largest element from the left of the list to the right. The algorithm is of the order O(n2).

This algorithm is inefficient for large collections, and it performs worse than the insertion sort algorithm.

Golang Selection Sort Algorithm

The following code shows the implementation of the SelectionSorter function, which takes the collection to be sorted.

Let's create a file named "selection_sort.go" and add the following source code to it:


package main

// importing fmt package
import (
	"fmt"
)

// Selection Sorter method
func SelectionSorter(elements []int) {

	var i int
	for i = 0; i < len(elements)-1; i++ {
		var min int
		min = i
		var j int
		for j = i + 1; j <= len(elements)-1; j++ {
			if elements[j] < elements[min] {
				min = j
			}
		}
		swap(elements, i, min)
	}
}

// swap method
func swap(elements []int, i int, j int) {
	var temp int
	temp = elements[j]
	elements[j] = elements[i]
	elements[i] = temp
}

//main method
func main() {
	var elements []int
	elements = []int{11, 4, 18, 6, 19, 21, 71, 13, 15, 2}
	fmt.Println("Before Sorting ", elements)
	SelectionSorter(elements)
	fmt.Println("After Sorting", elements)
}

Run the following command to execute the selection_sort.go file:

G:\GoLang\examples>go run selection_sort.go
Before Sorting  [11 4 18 6 19 21 71 13 15 2]
After Sorting [2 4 6 11 13 15 18 19 21 71]

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course