排序是将一组数据,以指定的顺序进行排列的过程,常见的排序:

  1. 冒泡排序;
  2. 选择排序;
  3. 插入排序;
  4. 快速排序。

冒泡排序可参考Go面试: 实现冒泡排序 (Golang经典编程案例)

插入排序可参考:用Go语言 轻松实现插入排序 (Golang经典编程案例)

快速排序可参考:用Go语言 实现快速排序 (Golang经典编程案例)

选择排序代码如下

package main
import (
	"fmt"
)
//编写函数selectSort 完成排序
func SelectSort(arr *[6]int) {

	for j := 0; j < len(arr)-1; j++ {
		max := arr[j]
		maxIndex := j
		//2. 遍历后面 1---[len(arr) -1] 比较
		for i := j + 1; i < len(arr); i++ {
			if max < arr[i] { //找到真正的最大值
				max = arr[i]
				maxIndex = i
			}
		}
		//交换
		if maxIndex != j {
			arr[j], arr[maxIndex] = arr[maxIndex], arr[j]
		}
		//fmt.Printf("第%d次 %v\n", j+1 ,*arr)
	}
}
func main() {
	//定义一个数组 , 从大到小
	arr := [6]int{10, 34, 19, 100, 80, 789}

	fmt.Println("排序前:",arr)
	SelectSort(&arr)
	fmt.Println("排序后:",arr)
}

执行结果如下图:
在这里插入图片描述

Logo

一站式虚拟内容创作平台,激发创意,赋能创作,进入R空间,遇见同道,让优质作品闪耀发光。​

更多推荐