在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
刚开始接触go语言,有些不适应,整体和C有些相像,所以学起来也不太困难,但是刚接触也感觉到了go在很多方面的强大。掌握了go的基本语法,简单写个归并排序练习一下: 1 package main 2 3 import ( 4 "fmt" 5 ) 6 7 func hebing(arr []int8, left int8, mid int8, right int8) { 8 var arr2 [10]int8 9 i, j := left, mid + 1 10 cnt := 0 11 for i <= mid && j <= right { 12 if arr[i] < arr[j] { 13 arr2[cnt] = arr[i] 14 cnt += 1 15 i += 1 16 } else { 17 arr2[cnt] = arr[j] 18 cnt += 1 19 j += 1 20 } 21 } 22 for i <= mid { 23 arr2[cnt] = arr[i] 24 cnt += 1 25 i += 1 26 } 27 for j <= right { 28 arr2[cnt] = arr[j] 29 cnt += 1 30 j += 1 31 } 32 for tm1, tm2 := 0, left; tm2 <= right; tm1, tm2 = tm1 + 1, tm2 + 1 { 33 arr[tm2] = arr2[tm1] 34 } 35 } 36 37 func mergesort(arr []int8, left int8, right int8) { 38 if left >= right { 39 return 40 } 41 mid := (left + right) / 2 42 fmt.Println(left, mid, right) 43 mergesort(arr, left, mid) 44 mergesort(arr, mid + 1, right) 45 hebing(arr, left, mid, right) 46 } 47 48 func main() { 49 var arr = []int8{1, 4, 2, 5, 3} 50 mergesort(arr, 0, 4) 51 fmt.Println(arr) 52 }
|
请发表评论