##切片
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
//切片slice的创建
arr := [...]int{0,1,2,3,4,5}
arr1 := []int{0,1,2,3,4,5}
arr2 := make([]int,6,8)
arr3 := make([]int,6)
fmt.Printf("长度len:%d, 容量cap:%d \n",len(arr),cap(arr)) //6 6
fmt.Printf("长度len:%d, 容量cap:%d \n",len(arr1),cap(arr1)) //6 6
fmt.Printf("长度len:%d, 容量cap:%d \n",len(arr2),cap(arr2)) //6 8
fmt.Printf("长度len:%d, 容量cap:%d \n",len(arr3),cap(arr3)) //6 6
//切片的截取
//下标 [low:high:max] [low,high) len=high-low cap=max-low
s := arr[:]
fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s)) //[0 1 2 3 4 5] len:6 cap:6
s = arr[1:3:6]
fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s)) //[1 2] len:2 cap:5
s = arr[:5]
fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s)) //[0 1 2 3 4] len:5 cap:6
s = arr[1:]
fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s)) //[1 2 3 4 5] len:5 cap:5
//切片是指向底层"数组"的指针
fmt.Println(arr) //[0 1 2 3 4 5]
s1 := arr[1:5:6]
s1[2] = 333
fmt.Println(arr) //[0 1 2 333 4 5]
//追加
var slice []int
slice = append(slice,1)
slice = append(slice,2)
slice = append(slice,3)
slice = append(slice,1)
fmt.Println(slice)
//copy
src := []int{1,1}
dest := []int{2,2,2,2,2}
copy(dest,src)
fmt.Println(dest) //[1 1 2 2 2]
//切片作为函数参数是引用传递
ss := []int{1,2,3,4,5}
initData(ss)
bubbleSort(ss)
fmt.Println(ss)
}
func initData(s []int){
//设置随机数种子
rand.Seed(time.Now().UnixNano())
for i,_ := range s{
s[i] = rand.Intn(10)
}
}
func bubbleSort(s []int){
for i := 0; i < len(s)-1; i++{
for j := 0; j < len(s)-1-i; j++{
if s[j] > s[j+1] {
s[j],s[j+1] = s[j+1],s[j]
}
}
}
}