How to implement selection sort in Go

Sorting is a fundamental operation in computer science that involves arranging a collection of elements in a specific order. There are numerous sorting algorithms available, each with its own strengths and weaknesses. One such algorithm is selection sort, which though not the most efficient, provides a simple way to understand the sorting process and is often used as a teaching tool.

Understanding selection sort

Selection sort is an in-placeAn in-place algorithm is one that modifies or rearranges the input data directly, without requiring additional memory proportional to the input size. comparison sorting algorithm that divides the input list into two parts: the sorted portion and the unsorted portion. The basic idea is to repeatedly find the minimum (or maximum) element from the unsorted portion and move it to the end of the sorted portion. This process is continued until the entire list is sorted.

The algorithm's key steps:

  1. Find the minimum element in the unsorted portion.

  2. Swap the found minimum element with the first element in the unsorted portion.

  3. Expand the sorted portion by moving the boundary one element to the right.

Selection Sort
Selection Sort

While selection sort is easy to understand, it's not very efficient for large datasets due to its quadratic time complexity. Its worst-case and average-case time complexitiesTime complexity is a measure of the amount of time an algorithm takes to execute as a function of the input size. are O(n2)O(n^2), where 'n' is the number of elements in the list. This makes it impractical for sorting large collections compared to more advanced sorting algorithms like Quick Sort or Merge Sort.

The space complexity of the selection sort algorithm is O(1)O(1), which means it requires a constant amount of extra space that doesn't depend on the input size. In other words, the amount of memory used by the algorithm remains relatively constant regardless of the number of elements being sorted.

Implementation in Go

Let's now implement the selection sort algorithm in Go. We'll assume that we are sorting a slice of integers in ascending order.

package main
import "fmt"
func selectionSort(arr []int) {
n := len(arr)
for i := 0; i < n-1; i++ {
// Find the minimum element in the unsorted portion
minIndex := i
for j := i + 1; j < n; j++ {
if arr[j] < arr[minIndex] {
minIndex = j
}
}
// Swap the found minimum element with the first element in the unsorted portion
arr[i], arr[minIndex] = arr[minIndex], arr[i]
}
}
func main() {
// Example unsorted slice
unsorted := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Unsorted slice:", unsorted)
// Apply Selection Sort
selectionSort(unsorted)
fmt.Println("Sorted slice:", unsorted)
}
Selection Sort in Go

Code explanation

  • Lines 8–19: This starts an outer loop that iterates through the elements of the input slice, up to the second-to-last element. This loop represents the process of expanding the sorted portion.

    • minIndex := i: Initializes the variable minIndex with the current index i. This index represents the smallest element found so far in the unsorted portion of the slice.

  • Lines 11–15: The for j := i + 1; j < n; j++ This nested loop iterates through the remaining unsorted portion of the slice, starting from the element after the current index i.

    • if arr[j] < arr[minIndex] {: Compares the value of the element at index j with the value of the current minimum element (arr[minIndex]). If the element at index j is smaller, we update minIndex to j, which means we've found a new minimum element in the unsorted portion.

  • Lines 15–18: The arr[i], arr[minIndex] = arr[minIndex], arr[i]: After the inner loop completes, this line swaps the element at the index i with the minimum element found in the unsorted portion (arr[minIndex]). This effectively moves the smallest unsorted element to its correct position in the sorted portion.

Conclusion

While selection sort might not be the fastest sorting algorithm available, it serves as a valuable learning tool for understanding the sorting process. It showcases the importance of selecting the right algorithm for the task at hand, especially when dealing with larger datasets. In real-world scenarios, using more efficient algorithms like quick sort or merge sort is generally recommended for better performance.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved