Golang. Selection Sort


Selection sort is a simple sorting algorithm that repeatedly selects the minimum item from the unsorted part of the list and swaps it with the first unsorted item.

Example code in Go:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	r := bufio.NewReader(os.Stdin)

	strInput, _ := r.ReadString('\n')

	strInput = strings.TrimSpace(strInput)

	strSlice := strings.Split(strInput, " ")
	var nums []int

	for _, v := range strSlice {
		num, _ := strconv.Atoi(v)
		nums = append(nums, num)
	}

	// Selection Sort
	// 1) go through slice and find lowest value
	// 2) put lowest value at the beginning of slice by swapping with current one

	for i := 0; i < len(nums); i++ {
		minIndex := i
		for j := i; j < len(nums); j++ {
			if nums[j] < nums[minIndex] {
				minIndex = j
			}
		}
		nums[i], nums[minIndex] = nums[minIndex], nums[i]
	}

	fmt.Println(nums)
}

Ok, lets go!

  1. For each iteration of the outer loop (for i...), the inner loop (for j...) goes over the unsorted part of the fragment nums, starting from the current index i and ending with the end of the slice.
  2. Variable j serves as an index of the current iteration in the inner loop, where we check if the value at nums[j] is less than the value at the current minimum index nums[minIndex].
  3. If nums[j] is less, we update minIndex to the value of j, noting the new minimum value.
  4. After the end of the inner loop, the outer loop changes the value by the current index i to the value by the minimal index nums[minIndex], placing the minimal value in the sorted part of the fragment nums at position i.

 


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.