golang selection_sort
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang selection_sort相关的知识,希望对你有一定的参考价值。
# 选择排序
# 寻找最小的元素
def find_smallest(arr: list) -> int:
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
# 选择排序
def selection_sort(arr: list) -> list:
new_arr = []
for i in range(len(arr)):
smallest_index = find_smallest(arr)
new_arr.append(arr.pop(smallest_index))
return new_arr
if __name__ == '__main__':
print(selection_sort([1, 3, 5, 1, 2, 3, 6, 3]))
package main
import "fmt"
func findSmallest(arr []int) int {
smallest := arr[0]
smallestIndex := 0
for i, v := range arr {
if v < smallest {
smallest = v
smallestIndex = i
}
}
return smallestIndex
}
func selectionSort(arr []int) []int {
newArr := make([]int, 0)
for len(arr) > 0 {
smallestIndex := findSmallest(arr)
newArr = append(newArr, arr[smallestIndex])
arr = append(arr[0:smallestIndex], arr[smallestIndex+1:]...)
}
return newArr
}
func main() {
fmt.Println(selectionSort([]int{3,5,1,2,4,6,3}))
}
c_cpp selection_sort
void selection_sort(int* tab, int size)
{
int min_index;
for (int i = 0; i < size - 1; i += 1) {
min_index = i;
for (int j = min_index + 1; j < size; j += 1) {
if (tab[j] < tab[min_index]) {
min_index = j;
}
}
swap(&tab[i], &tab[min_index]);
}
}
以上是关于golang selection_sort的主要内容,如果未能解决你的问题,请参考以下文章
选择排序(selection_sort)——Python实现
排序算法
排序算法
Golang 学习之路
Golang 入门
Golang入门到项目实战 第一个golang应用