分享
Golang - SelectionSort
zhangle234 · · 2075 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
//We start selection sort by scanning the entire list to
//find its smallest element and exchange it with the first
//element, putting the smallest element in its final position in
//the sorted list. Then we scan the list, starting with the second
//element, to find the smallest among the last n-1 elements
//and exchange it with the second element, putting the second
//smallest element in its final position.
//Generally, on the ith pass through the list, which we number from 0 to
//n-2, the algorithm searches for the smallest item among the n-i elements
//and swap it with A.
//After n-1 passes, the list is sorted.
package main
import (
"fmt"
)
//Sorts a given slice by selection sort
//Input: A slice A[0..n-1] of orderable elements
//Output: The original slice after sorted in nondecreasing order
func SelectionSort(A []int) []int {
length := len(A)
for i := 0; i < length-1; i++ {
min := i
for j := i + 1; j < length; j++ {
if A[min] > A[j] {
min = j
}
}
A[i], A[min] = A[min], A[i]
}
return A
}
func main() {
A := []int{1, 10, 9, 8, 7, 44, 2, 3, 33}
fmt.Println("The slice before sorted : ", A)
fmt.Println("The slice after sorted : ", SelectionSort(A))
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信2075 次点击
下一篇:Go基础学习-goroutine
0 回复
暂无回复
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
//We start selection sort by scanning the entire list to
//find its smallest element and exchange it with the first
//element, putting the smallest element in its final position in
//the sorted list. Then we scan the list, starting with the second
//element, to find the smallest among the last n-1 elements
//and exchange it with the second element, putting the second
//smallest element in its final position.
//Generally, on the ith pass through the list, which we number from 0 to
//n-2, the algorithm searches for the smallest item among the n-i elements
//and swap it with A.
//After n-1 passes, the list is sorted.
package main
import (
"fmt"
)
//Sorts a given slice by selection sort
//Input: A slice A[0..n-1] of orderable elements
//Output: The original slice after sorted in nondecreasing order
func SelectionSort(A []int) []int {
length := len(A)
for i := 0; i < length-1; i++ {
min := i
for j := i + 1; j < length; j++ {
if A[min] > A[j] {
min = j
}
}
A[i], A[min] = A[min], A[i]
}
return A
}
func main() {
A := []int{1, 10, 9, 8, 7, 44, 2, 3, 33}
fmt.Println("The slice before sorted : ", A)
fmt.Println("The slice after sorted : ", SelectionSort(A))
}