Go – Selection Sort in Golang

Hello everyone, in this tutorial, we will learn how to write a simple Selection Sort in Golang programming language. This example program has been tested and shared in the same post.

Selection Sort in Golang

What is Selection Sort?

The selection sort algorithm sorts an items by repeatedly finding the minimum element from unsorted items and putting it at the beginning. The algorithm maintains two subarrays in a given array. The following example explains how it works.

Function – Selection Sort in Golang

The below function is responsible to sort a given numbers array by using Selection Sort algorithm.

func selectionSort(numbers []int) []int {

	var mid_index int;

	for i := 0; i < len(numbers); i++ {

		mid_index = i

		for j := i + 1; j < len(numbers); j++ {
			if numbers[j] < numbers[mid_index] {
				mid_index = j
			}
		}

		temp := numbers[mid_index]
		numbers[mid_index] = numbers[i]
		numbers[i] = temp
	}

	return numbers
}

Full Example

package main

import "fmt"

func selectionSort(numbers []int) []int {

	var mid_index int;

	for i := 0; i < len(numbers); i++ {

		mid_index = i

		for j := i + 1; j < len(numbers); j++ {
			if numbers[j] < numbers[mid_index] {
				mid_index = j
			}
		}

		temp := numbers[mid_index]
		numbers[mid_index] = numbers[i]
		numbers[i] = temp
	}

	return numbers
}

// main function
func main() {

	fmt.Println("Selection Sort \n")

	// creating an integer array with values
	number := []int{2, 1, 4, 6, 5, 3, 8, 7, 10, 9}

	fmt.Println("Before Sorting:", number)

	// calling the selectionSort function
	number = selectionSort(number)

	fmt.Println("\nAfter Sorting:", number)
}



Output

Selection Sort 

Before Sorting: [2 1 4 6 5 3 8 7 10 9]

After Sorting: [1 2 3 4 5 6 7 8 9 10]

References