Tuesday, August 7, 2018

Implementing Selection Sort in Golang

What Is Selection Sort?
Selection sort is sorting algorithm specifically an in-place comparison sort. The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right..

Time Complexity
The time complexity for this algorithm is O(N^2) and making it inefficient on large lists.

Implementation
package main

import (
    "fmt"
    "math/rand"
    "time"x
)

func main() {
    slice := generateSlice(20)
    fmt.Println("\n--- Unsorted --- \n\n", slice)
    selectionsort(slice)
    fmt.Println("\n--- Sorted ---\n\n", slice, "\n")
}

// Generates 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]
    }
}
Result:






Other Topics: