排序算法:Insertion Sort和Merge Sort in GoLang
来源:互联网 发布:地址栏执行js 编辑:程序博客网 时间:2024/06/07 00:18
最近在学习算法导论,课程上讲了两种排序算法,分别是插入排序法和合并选择法
下面用GO语言实现,不过实现得不够简洁,这位作者的更好http://austingwalters.com/merge-sort-in-go-golang/
package sort//InsertionSort 插入排序 n^2func InsertionSort(arr []int) {if len(arr) < 2 {return}for j := 1; j < len(arr); j++ {key := arr[j]i := j - 1for i >= 0 && arr[i] > key {arr[i+1] = arr[i]i--}arr[i+1] = key}}//MergeSort 合并选择算法 nlgnfunc MergeSort(arr []int) (sorted []int) {n := len(arr)if n == 1 {return arr} sorted1 := MergeSort(arr[0 : n/2]) sorted2 := MergeSort(arr[n/2:]) return mergeSortedList(sorted1,sorted2)}func mergeSortedList(arr1, arr2 []int) []int {len1 := len(arr1)len2 := len(arr2)var pointer1, pointer2 intresult := make([]int, len1+len2)var index = 0 for (pointer1 < len1) && (pointer2 < len2) {if arr1[pointer1] < arr2[pointer2] {result[index] = arr1[pointer1] pointer1++} else {result[index] = arr2[pointer2] pointer2++}index++}//arr1或者arr2被提取完时if pointer1 == len1 {for i := pointer2; i < len2; i++ {result[index] = arr2[i]index++}} else {for i := pointer1; i < len1; i++ {result[index] = arr1[i]index++}} return result}
觉得实现的不够简洁,修改了一下,采用添加哨兵的方式来减少程序中的判断
//这个版本性能更好,加入了哨兵牌,就可以不用做过顶的检查func mergeSortedList2(arr1, arr2 []int) []int { var p1, p2 int length := len(arr1) + len(arr2) result := make([]int, length) var arr1M, arr2M []int arr1M = append(arr1M, arr1...) arr1M = append(arr1M, math.MaxInt64) arr2M = append(arr2M, arr2...) arr2M = append(arr2M, math.MaxInt64) for index := 0; index < length; index++ { if arr1M[p1] < arr2M[p2] { result[index] = arr1M[p1] p1++ } else { result[index] = arr2M[p2] p2++ } } return result}
下面是测试代码
package sortimport( "testing" "fmt")func TestSort(t *testing.T) { fmt.Println("开始测试") arr := []int{10, 7, 1, 5, 11, 3, 100, 250, 110, 13, 0, -88, -7} InsertionSort(arr) fmt.Println(arr)}func TestMergeSort(t *testing.T) { fmt.Println("开始测试") arr := []int{10, 7, 1, 5, 11, 3, 100, 250, 110, 13, 0, -88, -7} result := MergeSort(arr) fmt.Println(result)}
0 0
- 排序算法:Insertion Sort和Merge Sort in GoLang
- merge sort in golang
- Insertion Sort, Merge Sort
- Merge Sort in Go (Golang)
- 结合归并排序和插入排序 Merge with Insertion Sort
- 插入排序算法Insertion-Sort
- Insertion Sort and Merge Sort
- Insertion sort and Merge sort
- Insertion Sort and Merge Sort
- Sort List (merge & Insertion)
- 算法排序--插入排序(insertion sort)
- 经典排序算法:插入排序Insertion sort
- 排序算法---插入排序(Insertion Sort)
- Bubble sort, Insertion sort, merge sort, quick sort, heap sort
- 排序算法算法之Insertion Sort
- 【算法】归并排序 merge sort
- 归并(Merge Sort)排序算法
- 算法-归并排序(Merge-Sort)
- 编写可读代码的艺术 (12)
- 机器学习的数学基础(一)—— 期望、方差、协方差与相关系数
- 日常代码
- typedef和#define的区别及用法
- Objective-C编码规范[译]
- 排序算法:Insertion Sort和Merge Sort in GoLang
- XML初步
- 2016第七届蓝桥杯C/C++ B组省赛第三题:凑算式
- phpstorm安装和调试
- <div+css页面布局课堂笔记>11---页面布局网站首页设计实例__终极版(仿csdn首页)
- 中文 iOS/Mac 开发博客列表
- UML系列图--用例图
- mysql连接数据库指令
- Oracle 查看表空间的大小及使用情况sql语句