Golang program for implementation of Selection Sort
This sorting algorithm begins by finding the smallest element in an array and interchanging it with data at, for instance, array index [0]. Starting at index 0, we search for the smallest item in the list that exists between index 1 and the index of the last element. When this element has been found, it is exchanged with the data found at index 0. We simply repeat this process until the list becomes sorted.
Example
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
slice := generateSlice(20)
fmt.Println("\n--- Unsorted --- \n\n", slice)
selectionsort(slice)
fmt.Println("\n--- Sorted ---\n\n", slice, "\n")
}
// Generates a slice of size, size filled with random numbers
func generateSlice(size int) []int {
slice := make([]int, size, size)
rand.Seed(time.Now().UnixNano())
for i := 0; i < size; i++ {
slice[i] = rand.Intn(999) - rand.Intn(999)
}
return slice
}
func selectionsort(items []int) {
var n = len(items)
for i := 0; i < n; i++ {
var minIdx = i
for j := i; j < n; j++ {
if items[j] < items[minIdx] {
minIdx = j
}
}
items[i], items[minIdx] = items[minIdx], items[i]
}
}
Output
--- Unsorted ---
[-683 81 -167 555 -651 -234 -251 470 280 -237 297 -188 -707 497 -261 186 411 466 154 -196]
--- Sorted ---
[-707 -683 -651 -261 -251 -237 -234 -196 -188 -167 81 154 186 280 297 411 466 470 497 555]
Most Helpful This Week
Web Application to Get Trending Hashtags Near a Location
GO language program with example of String Compare function
Example: How to use ReadFull from IO Package in Golang?
Find out how many logical processors used by current process
Read and Write Fibonacci series to Channel in Golang
Illustration of the dining philosophers problem in Golang
How do you handle HTTP server HTTP/2 in Go?
Go program to find TXT records of a domain
Illustration of Cigarette Smokers Problem in Golang
Example: How to use TeeReader from IO Package in Golang?