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:
How to build NGINX RTMP module, Setup Live Streaming with NGINX RTMP module, Publishing Stream with Open Broadcaster Software (OBS), Create Adaptive Streaming with NGINX RTMP, Implementing Filtergraph in Streaming with NGINX RTMP, How to Implement Running Text in Streaming with NGINX RTMP, How to build OpenSceneGraph with Code::Blocks, How to build OpenSceneGraph with Visual Studio 2010, Building Geometry Model, How to run OpenSceneGraph with Netbean IDE 8.2 C++, Rendering Basic Shapes, Using OSG Node to Load 3D Object Model, Rendering 3D Simulator with OpenSceneGraph, How to compile wxWidgets with Visual Studio 2010, How to Setup Debugging in Golang with Visual Code
No comments:
Post a Comment