go语言 切片做函数的参数

通过操作元素的地址,改变元素 

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func initData(s []int) {
	//设置种子
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < len(s); i++ {
		s[i] = rand.Intn(100) // 100以内的随机数
	}

}

func main() {
	n := 10
	// 创建一个切片,长度为len
	s := make([]int, n)

	initData(s) // 数组初始化
	fmt.Println("排序前: s = ", s)

	// 冒泡排序
	n = len(s)
	for i := 0; i < n-1; i++ {
		for j := 0; j < n-1-i; j++ {
			if s[j] > s[j+1] {
				s[j], s[j+1] = s[j+1], s[j]
			}
		}
	}
	fmt.Println("排序后: s = ", s)
}

猜你喜欢

转载自blog.csdn.net/m0_38068812/article/details/85224414
今日推荐