# golang实现直接插入排序算法

rufidmx · · 3311 次点击 · · 开始浏览

```package main

import(
"container/list"
"fmt"
)

var old []int = []int{432,432432,4234,333,333,21,22,3,30,8,20,2,7,9,50,80,1,4}
func main(){
fmt.Println("old array:",old)
res,_ := InsertionSort(old)
i := 0
for e := res.Front(); nil != e; e = e.Next(){
//fmt.Println("[", i,"]: ",e.Value.(int))
fmt.Printf("[%d]: %d\n",i, e.Value.(int))
i += 1
}
}

func InsertionSort(old []int)(sortedData *list.List, err error){
sortedData = list.New()
sortedData.PushBack(old[0])
size := len(old)
for i := 1; i < size; i++{
v := old[i]
e := sortedData.Front()
for nil != e{
if e.Value.(int) >= v{
sortedData.InsertBefore(v, e)
break
}
e = e.Next()
}
//the biggest,put @v on the back of the list
if nil == e{
sortedData.PushBack(v)
}
}

return
}
```

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

```package main

import(
"container/list"
"fmt"
)

var old []int = []int{432,432432,4234,333,333,21,22,3,30,8,20,2,7,9,50,80,1,4}
func main(){
fmt.Println("old array:",old)
res,_ := InsertionSort(old)
i := 0
for e := res.Front(); nil != e; e = e.Next(){
//fmt.Println("[", i,"]: ",e.Value.(int))
fmt.Printf("[%d]: %d\n",i, e.Value.(int))
i += 1
}
}

func InsertionSort(old []int)(sortedData *list.List, err error){
sortedData = list.New()
sortedData.PushBack(old[0])
size := len(old)
for i := 1; i < size; i++{
v := old[i]
e := sortedData.Front()
for nil != e{
if e.Value.(int) >= v{
sortedData.InsertBefore(v, e)
break
}
e = e.Next()
}
//the biggest,put @v on the back of the list
if nil == e{
sortedData.PushBack(v)
}
}

return
}
```