直接插入排序算法golang实现版本:
插入算法概要:
建立一个空的链表,首先在要排序的数组中随便拿出来一个数据,放在新建链表的开头,然后不停的从原数组中
获取数据,并和链表中的数据进行比较,大就放在链表的右端,小就放在链表的左端,一直循环直到结束为止,
排序完成。
package main import( "container/list" "fmt" ) var old []int = []int{432,432432,4234,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",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 }