## DEV Community 👩‍💻👨‍💻

Kuldeep Singh

Posted on • Updated on • Originally published at programmingeeksclub.com

# selection sort algorithm

Selection sort algorithm is a simple sorting algorithm. Selection sort algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.

The algorithm maintains two subarrays in a given array.

• The subarray which already sorted.
• The remaining subarray was unsorted.

Flowchart of selection sort algorithm

## How it works?

• Set minimum value(min_index) to location 0.
• Traverse the array to find the minimum element in the array.
• If any element smaller than (min_index) is found then swap both the values.
• Increment (min_index) to point to the next element.
• Repeat until the array is sorted.

Algorithm Implementation in Golang

``````package main

import (
"fmt"
)

func selectionSort(arr []int) {
var i, j, min_index int
for i = 0; i < len(arr)-1; i++ {
min_index = i
for j = i + 1; j < len(arr); j++ {
if arr[j] < arr[min_index] {
min_index = j
}
}

// if min_index is not equals to i then swap the indexes
if min_index != i {
arr[i], arr[min_index] = arr[min_index], arr[i]
}
}
}

func main() {
arr := []int{12, 23, 34, 43, 4, 34, 24, 3, 53, 25454, 64}
fmt.Println("before selection sort", arr)
selectionSort(arr)
fmt.Println("after selection sort", arr)
}
``````