golang 算法 插入排序

来源:互联网 发布:青少年性犯罪数据 编辑:程序博客网 时间:2024/03/29 18:37

mian.go

package mainimport ("container/list""fmt""sort")func main() {num := []int{432, 432432, 0, 4234, 333, 333, 21, 22, 3, 30, 8, 20, 2, 7, 9, 50, 80, 1, 4}insertionSort1(num)fmt.Println(num)}// 插入排序func insertionSort1(nums []int) {for j := 1; j < len(nums); j++ {// 增加判断减少循环if nums[j] < nums[j-1] {key := nums[j]i := j - 1for ; i >= 0 && nums[i] > key; i-- {nums[i+1] = nums[i]}nums[i+1] = key}}}func insertionSort2(old []int) {insertionSort(old)}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 listif nil == e {sortedData.PushBack(v)}}return}func insertionSort3(nums []int) {for i := 1; i < len(nums); i++ {if nums[i] < nums[i-1] {j := i - 1temp := nums[i]for j >= 0 && nums[j] > temp {nums[j+1] = nums[j]j--}nums[j+1] = temp}}}func insertionSort4(nums []int) {sort.Ints(nums)}func InsertionSort5(nums []int) {n := len(nums)if n < 2 {return}for i := 1; i < n; i++ {for j := i; j > 0 && nums[j] < nums[j-1]; j-- {swap(nums, j, j-1)}}}func swap(slice []int, i int, j int) {slice[i], slice[j] = slice[j], slice[i]}

main_test.go

package mainimport ("testing")var (nums []int = []int{0, 20, 10, 25, 15, 30, 28, 55, 432, 432432, 4234, 333, 333, 21, 22, 3, 30, 8, 20, 2, 7, 9, 50, 80, 1, 4})func BenchmarkInsertionSort1(b *testing.B) {for i := 0; i < b.N; i++ {insertionSort1(nums)}}func BenchmarkInsertionSort2(b *testing.B) {for i := 0; i < b.N; i++ {insertionSort2(nums)}}func BenchmarkInsertionSort3(b *testing.B) {for i := 0; i < b.N; i++ {insertionSort3(nums)}}func BenchmarkInsertionSort4(b *testing.B) {for i := 0; i < b.N; i++ {insertionSort4(nums)}}func BenchmarkInsertionSort5(b *testing.B) {for i := 0; i < b.N; i++ {InsertionSort5(nums)}}


0 0