1.实现一个插入排序 核心思路是抽到的牌与前面的牌进行比较,如果抽到的牌小,那么就互相交换位置.(正序排列)
1: func insert_sort(a []int) []int {
2: for i:=1;i<len(a);i++ {
3: for j:=i;j>0;j-- {
4: if a[j] < a[j-1]{
5: a[j], a[j-1] = a[j-1], a[j]
6: }
7: }
8: }
9: return a
10: }
11:
12: func main() {
13: var i []int = []int{8, 3, 2, 9, 4, 6, 10, 0}
14: insert_sort(i)
15: fmt.Println(i)
16: }
2.实现一个选择排序
核心思路是每一轮扫描都选出最小(最大)的数放在前面(后面)
1: package main
2: import (
3: "fmt"
4: )
5: func select_sort(a []int) {
6: for i:=0; i < len(a); i++ {
7: for j:=i+1; j<len(a); j++ {
8: if a[i] > a[j]{
9: a[i], a[j] = a[j], a[i]
10: }
11: }
12: }
13: }
14: func main() {
15: var i []int = []int{8, 3, 2, 9, 4, 6, 10, 0}
16: select_sort(i)
17: fmt.Println(i)
18: }
3.实现一个冒泡排序
核心思路是每一轮冒泡都把最大(或者最小)的数放入后面(前面)
1: func bubble_sort(a []int) {
2: for i:=0; i < len(a); i++ {
3: for j:=0;j<len(a)-1;j++{
4: if a[j] > a[j+1] {
5: a[j], a[j+1] = a[j+1], a[j]
6: }
7: }
8: }
9: }
|
请发表评论