Implement selection sort in Go language. Traverse the array starting from the first data. During each traversal, compare whether it is the smallest (largest) number among the numbers from the current position to the end position. If it is not the smallest (largest) number, record it. Finally, swap the current traversed data with the smallest number among the numbers from the current position to the end position. After completing the traversal, you will get an ordered array in ascending (descending) order.
Source Code
Increasing order from smallest to largest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcselectSortDesc(arr []int) { for i := 0; i < len(arr); i++ { var minNumber int = arr[i] var minIndex int = i for j := i; j < len(arr); j++ { if minNumber > arr[j] { minNumber = arr[j] minIndex = j } } if minIndex != i { arr[i], arr[minIndex] = arr[minIndex], arr[i] } } }
Decreasing order from largest to smallest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcselectSortAsc(arr []int) { for i := 0; i < len(arr); i++ { var maxNumber int = arr[i] var maxIndex int = i for j := i; j < len(arr); j++ { if maxNumber < arr[j] { maxNumber = arr[j] maxIndex = j } } if maxIndex != i { arr[i], arr[maxIndex] = arr[maxIndex], arr[i] } } }