Selection Sort
Continuing my study of algorithms, I can now explain the selection sort algorithm to you.
Selection sort is a simple algorithm. It works by finding the smallest element in an array, adding it to a new array, and removing it from the original array. This process is repeated until the original array is empty. Once the original array is empty, the new array will contain the elements in sorted order.
In this example, I am not focusing on performance but rather on the simplicity of the algorithm.
Here is the array we will use for our example:
arr := []int{100, 5, 3, 6, 2, 10}
For the next step I create the function that receive this arr and return the sorted array:
func orderIntArray(arr []int) []int {
var result []int
var min int
for len(arr) > 0 {
min = getSmallerItem(arr)
result = append(result, arr[min])
arr = remove(arr, min)
}
return result
}
The getSmallerItem
function is responsible to get the index of the smallest element in the array:
func getSmallerItem(arr []int) int {
var min int = arr[0]
var pos int
for i := 1; i < len(arr); i++ {
if arr[i] < min {
min = arr[i]
pos = i
}
}
return pos
}
The getSmallerItem
function compare the element in the array with the min
variable,
if the element is smaller than the min
variable, the min
variable will be updated with the
element value and the pos
variable will be updated with the index of the element.
When the loop finish, the pos
variable will be returned.
The remove
function is responsible to remove the element from the array:
func remove(s []int, i int) []int {
s[i] = s[len(s)-1]
return s[:len(s)-1]
}
The remove
function receive the array and the index of the element that will be removed.
Now we can test the function:
func main() {
arr := []int{100, 5, 3, 6, 2, 10}
result := orderIntArray(arr)
fmt.Println(result) // return is [2 3 5 6 10 100]
}
This algorithm is not efficient, but is a good example to understand the selection sort algorithm.
I hope you enjoy this post, see you in the next one!