Golang : Selection sort example
The selection sort algorithm is an in-place comparison sort. What it does is that it loops a given slice and find the first smallest value, swaps it with the first element; loop and find the second smallest value again, swaps it with the second element, repeats third, fourth, fifth smallest values and swaps it.
Once everything is in correct order, the selection sort process will stop. Given the method of how it works, selection sort algorithm is inefficient on large lists.
Below is a simple implementation of selection sort in Golang. Here you go!
package main
import (
"fmt"
)
func selectionSort(randomSlice []int) {
var size = len(randomSlice)
for i := 0; i < size; i++ {
var min = i
// find the first, second, third, fourth...smallest value
for j := i; j < size; j++ {
if randomSlice[j] < randomSlice[min] {
min = j
}
}
// swap the smallest value the position of "i"
randomSlice[i], randomSlice[min] = randomSlice[min], randomSlice[i]
} // repeat till end of slice
}
func main() {
var randomInt = []int{10, 9, 8, 22, 11, 23, 9}
fmt.Println("Unsorted : ")
fmt.Println(randomInt)
fmt.Println("Selection Sorted : ")
selectionSort(randomInt)
fmt.Println(randomInt)
}
Output:
Unsorted :
[10 9 8 22 11 23 9]
Selection Sorted :
[8 9 9 10 11 22 23]
See also : Golang : Sort and reverse sort a slice of integers
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+33.7k Golang : Strip slashes from string example
+7.3k Golang : How to check variable or object type during runtime?
+8.3k Golang : How to generate Code 39 barcode?
+28k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+8.7k Golang : Identifying Golang HTTP client request
+6.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+8.8k Golang : Test a slice of integers for odd and even numbers
+9.1k Golang : Text file editor (accept input from screen and save to file)
+6.3k Golang : Rot13 and Rot5 algorithms example
+3.6k Adding Skype actions such as call and chat into web page examples
+9.5k Golang : Get local time and equivalent time in different time zone
+5.3k Golang : Break string into a slice of characters example