初识数组
func main() {
//定义一个数组
var nums [4]int
//数组的下标从0开始
nums[0] = 1
nums[1] = 2
nums[2] = 3
nums[3] = 4
fmt.Printf("%T\n", nums)
//通过下标获取数组的元素的
fmt.Println(nums[1])
fmt.Println(nums[2])
fmt.Println("数组的长度为", len(nums)) //长度
fmt.Println("数组的容量为", cap(nums)) //容量
nums[0] = 100
fmt.Println(nums)
}
数组的初始化
func main() {
//常规初始化
var arr1 = [5]int{1, 2, 3, 4, 5}
fmt.Println(arr1)
fmt.Println(arr1[2])
//快速定义数组
arr2 := [5]int{6, 7, 8, 9}
fmt.Println(arr2)
//...不确定数组大小
//编译器根据我们传入的值自动判断数组的大小
arr3 := [...]string{"zhounan", "hello", "daawei"}
fmt.Println(arr3)
fmt.Println(cap(arr3))
fmt.Println(len(arr3))
//通过下标赋值
arr4 := [5]int{1: 100, 4: 200}
fmt.Println(arr4)
}
遍历数组元素
func main() {
var arr1 = [5]int{1, 2, 3, 4, 5}
fmt.Println(arr1)
for i := 0; i < len(arr1); i++ {
fmt.Println(arr1[i])
}
for index, value := range arr1 {
fmt.Println(index, value)
}
}
数组是值类型
func main() {
num := 10
fmt.Printf("%T\n", num)
arr1 := [3]int{1, 2, 3}
arr2 := [2]string{"周南", "打阿伟"}
fmt.Printf("%T\n", arr1)
fmt.Printf("%T\n", arr2)
//值类型,拷贝 arr
num2 := num
fmt.Println(num, num2)
num2 = 20
fmt.Println(num, num2)
//数组是值传递类型
arr3 := arr1
fmt.Println(arr1, arr3)
arr3[2] = 100
fmt.Println(arr1, arr3)
}
冒泡排序优化
func main() {
//冒泡排序
arr := [5]int{5, 4, 2, 3, 1}
for j := 1; j < len(arr); j++ {
var isFlag bool = true
for i := 0; i < len(arr)-j; i++ {
if arr[i] < arr[i+1] {
arr[i], arr[i+1] = arr[i+1], arr[i]
isFlag = false
}
}
if isFlag {
break
}
fmt.Println(arr)
}
}
多维数组
func main() {
//[5]int
//[5][4]int二维数组
arr := [3][4]int{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
}
fmt.Println(arr[1][1])
for i := 0; i < 3; i++ {
for j := 0; j < 4; j++ {
fmt.Println(arr[i][j])
}
}
for i, v := range arr {
fmt.Println(i, v)
for _, v1 := range v {
fmt.Println(v1)
}
}
}