Go Program to Implement Selection Sort

Selection Sort is a simple comparison-based sorting algorithm. The main idea behind it is to divide the list into two parts: a sorted part and an unsorted part, then repeatedly pick the smallest (or largest, depending on sorting order) element from the unsorted sublist and move it to the end of the sorted sublist.

In this blog post, we will learn how to write a Go program to implement Selection Sort.

Program Steps

The main idea behind the Selection Sort is: 

1. For each iteration, find the minimum (or maximum) from the unsorted section of an array. 

2. Swap it with the leftmost unsorted element. 

3. Move the boundary between the sorted and unsorted regions one element to the right.

Code Program

package main

import "fmt"

// Function for the Selection Sort Algorithm
func selectionSort(arr []int) {
    length := len(arr)
    for i := 0; i < length-1; i++ {
        // Assume the min is the first number
        minIdx := i
        // Test against numbers after i to find the smallest number
        for j := i+1; j < length; j++ {
            if arr[j] < arr[minIdx] {
                minIdx = j
            }
        }
        // Swap the numbers.
        arr[i], arr[minIdx] = arr[minIdx], arr[i]
    }
}

func main() {
    array := []int{64, 25, 12, 22, 11}
    fmt.Println("Original Array:", array)

    selectionSort(array)
    fmt.Println("Sorted Array:", array)
}

Output:

Original Array: [64 25 12 22 11]
Sorted Array: [11 12 22 25 64]

Explanation

Initialization: The algorithm begins by assuming the first element (i.e., arr[0]) is the smallest. 

Finding Minimum: For each i, the algorithm then scans through the array from i+1 to the end of the array to find the index minIdx of the smallest element. 

Swapping: Once the index of the smallest (or largest, depending on sorting order) element is found, the algorithm swaps arr[i] with arr[minIdx]. 

Iteration: This process is repeated for each i from 0 to len(arr) - 2. 

End Result: At the end of all iterations, the array becomes sorted in ascending order. 

The primary advantage of Selection Sort is its simplicity. It performs well on smaller lists. However, for larger datasets, more efficient algorithms like Quick Sort, Merge Sort, or Built-in functions are recommended.

Comments