GoLang Program to Implement Selection Sort

GoLang Program to Implement Selection Sort

Sorting is a core concept in programming, and understanding how to arrange data in order is essential for building efficient applications. Selection Sort is one of the fundamental sorting algorithms that beginners often learn because of its simplicity and clear logic. It helps in grasping basic programming ideas such as loops, comparisons, and array manipulation.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Selection Sort works by repeatedly finding the smallest (or largest) element from the unsorted part of the list and placing it in the correct position. This process continues until the entire list is sorted. Although Selection Sort is not the most efficient algorithm for large datasets, it is highly useful for educational purposes and small-scale applications. Learning Selection Sort also builds a foundation for understanding more complex sorting algorithms like Merge Sort and Quick Sort.

Program 1: Selection Sort Using Simple Loops

In this first example, we implement Selection Sort using basic for loops. This method is the easiest way to understand how Selection Sort works step by step.

package main

import "fmt"

func main() {

    numbers := []int{29, 10, 14, 37, 13}

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

        minIndex := i

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

            if numbers[j] < numbers[minIndex] {
                minIndex = j
            }

        }

        numbers[i], numbers[minIndex] = numbers[minIndex], numbers[i]

    }

    fmt.Println("Sorted array:", numbers)

}

This program loops through the array and finds the smallest element in the unsorted portion. It then swaps this element with the first unsorted element. Beginners can easily follow the logic because the algorithm mimics a simple step-by-step approach to sorting. It’s a practical introduction to how comparisons and swaps can organize data efficiently.

Program 2: Selection Sort in Descending Order

Sometimes we need the largest elements to come first rather than last. This version of Selection Sort modifies the comparison to arrange elements in descending order.

package main

import "fmt"

func main() {

    numbers := []int{29, 10, 14, 37, 13}

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

        maxIndex := i

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

            if numbers[j] > numbers[maxIndex] {
                maxIndex = j
            }

        }

        numbers[i], numbers[maxIndex] = numbers[maxIndex], numbers[i]

    }

    fmt.Println("Sorted array in descending order:", numbers)

}

The only difference from the ascending version is that the program now searches for the maximum element in the unsorted portion of the array. Beginners can see how small changes in logic can achieve different results, which is a valuable lesson in algorithm flexibility.

Program 3: Selection Sort Using a Function

Creating a reusable function for Selection Sort makes your code cleaner and easier to maintain. In this example, we define a function that can sort any slice of integers.

package main

import "fmt"

func selectionSort(arr []int) {

    for i := 0; i < len(arr)-1; i++ {

        minIndex := i

        for j := i + 1; j < len(arr); j++ {

            if arr[j] < arr[minIndex] {
                minIndex = j
            }

        }

        arr[i], arr[minIndex] = arr[minIndex], arr[i]

    }

}

func main() {

    numbers := []int{29, 10, 14, 37, 13}

    selectionSort(numbers)

    fmt.Println("Sorted array using function:", numbers)

}

By using a function, beginners can practice modular programming, which is essential for building larger projects. The main logic remains the same, but encapsulating it in a function improves readability and reusability. This approach also makes it easy to sort different arrays without rewriting code.

Program 4: Selection Sort Using Recursion

Recursion is another way to implement algorithms, where a function calls itself to solve smaller parts of a problem. This version of Selection Sort demonstrates how recursion can be applied to sorting.

package main

import "fmt"

func selectionSortRec(arr []int, start int) {

    if start >= len(arr)-1 {
        return
    }

    minIndex := start

    for i := start + 1; i < len(arr); i++ {

        if arr[i] < arr[minIndex] {
            minIndex = i
        }

    }

    arr[start], arr[minIndex] = arr[minIndex], arr[start]

    selectionSortRec(arr, start+1)

}

func main() {

    numbers := []int{29, 10, 14, 37, 13}

    selectionSortRec(numbers, 0)

    fmt.Println("Sorted array using recursion:", numbers)

}

In this recursive version, the function sorts the array from the starting index to the end by finding the minimum element and swapping it. Then it calls itself with the next index. This teaches beginners how problems can be broken down into smaller tasks and solved systematically, helping them develop a deeper understanding of recursion.

Frequently Asked Questions (FAQ)

Selection Sort can seem simple at first, but beginners often have a few common questions.

Q1: What is Selection Sort?
Selection Sort is a sorting algorithm that repeatedly selects the smallest (or largest) element from the unsorted portion of the list and moves it to its correct position.

Q2: Why should beginners learn Selection Sort?
It is easy to understand and implement, making it a perfect starting point for learning sorting algorithms and basic array manipulation.

Q3: Is Selection Sort efficient for large datasets?
No, Selection Sort has a time complexity of O(n²), which makes it inefficient for large arrays. More advanced algorithms like QuickSort or MergeSort are faster for large datasets.

Q4: Can Selection Sort be used in real applications?
While it is rarely used in performance-critical applications, Selection Sort is useful for educational purposes, small datasets, and situations where simplicity is more important than speed.

Q5: How can I make Selection Sort better?
Using flags to check if the array is already sorted or combining it with other sorting algorithms can improve efficiency in some cases. Practicing with variations helps build a deeper understanding.

Conclusion

Selection Sort is a beginner-friendly algorithm that introduces core programming concepts like loops, comparisons, swaps, and recursion. By experimenting with different approaches, including ascending, descending, function-based, and recursive versions, beginners can gain a solid understanding of how sorting works.

Practicing these examples in GoLang allows learners to build confidence and develop a foundation for tackling more advanced algorithms. The key is to experiment, modify the programs, and observe the results, which will make sorting feel intuitive and approachable.

Scroll to Top