GO·NOTE

一份 Go 开发工程师的学习笔记

0%

有序数组种插入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

func main() {
array := []int{80, 60, 20, 10, 1}
fmt.Println(array[:4])
fmt.Println(InsertData(array, 2))
}

func InsertData(array []int, num int) []int {
for i := 0; i < len(array); i++ {
if num > array[i] {
arrayTmp := make([]int, len(array))
copy(arrayTmp, array)
array = append(append(arrayTmp[:i], num), array[i:]...)
break
}
if i == len(array)-1 {
array = append(array, num)
}
}
return array
}