选择排序算法是一种简单的排序算法。 选择排序算法是一种基于就地比较的算法,其中列表分为两部分,左端的排序部分和右端的未排序部分。 最初,已排序的部分是空的,未排序的部分是整个列表。
该算法在给定数组中维护两个子数组。
- 已经排序的子数组。
- 剩余的子数组未排序。
选择排序算法流程图
算法步骤:
- 将最小值(min_index)设置为位置 0。
- 遍历数组以找到数组中的最小元素。
- 如果找到任何小于 (min_index) 的元素,则交换两个值。
- 递增 (min_index) 以指向下一个元素。
- 重复直到数组排序。
Golang 中的算法实现
package main
import (
"fmt"
)
func selectionSort(arr []int) {
var i, j, min_index int
for i = 0; i < len(arr)-1; i++ {
min_index = i
for j = i + 1; j < len(arr); j++ {
if arr[j] < arr[min_index] {
min_index = j
}
}
// if min_index is not equals to i then swap the indexes
if min_index != i {
arr[i], arr[min_index] = arr[min_index], arr[i]
}
}
}
func main() {
arr := []int{12, 23, 34, 43, 4, 34, 24, 3, 53, 25454, 64}
fmt.Println("before selection sort", arr)
selectionSort(arr)
fmt.Println("after selection sort", arr)
}
输出:
选择排序前 [12 23 34 43 4 34 24 3 53 25454 64]
选择排序后 [3 4 12 23 24 34 34 43 53 64 25454]
谢谢阅读
关注七爪网,获取更多APP/小程序/网站源码资源!