Jquery中文网 www.jquerycn.cn
Jquery中文网 >  后端编程  >  Go语言  >  正文 golang 算法 插入排序

golang 算法 插入排序

发布时间:2021-04-15   编辑:www.jquerycn.cn
jquery中文网为您提供golang 算法 插入排序等资源,欢迎您收藏本站,我们将为您提供最新的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)
	}
}


到此这篇关于“golang 算法 插入排序”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
PHP学习之插入排序的实现
php插入排序的实现代码
golang 算法 插入排序
java排序算法
php 插入排序程序代码
php实用快速排序算法的实例代码
PHP 排序算法之插入排序
javascript常见排序算法实现代码
golang实现常用排序算法(一)
golang struct数组排序_Golang算法问题之数组按指定规则排序的方法分析

[关闭]