golang 算法 插入排序

mian.go

package main

import (
	"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 - 1
			for ; 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 list
		if 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 - 1
			temp := 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 main

import (
	"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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值