在学习go的过程中,正好在看《算法导论》,于是实现了一下插入排序:
package main
import ("fmt""rand""time")
func main () {arr := Random ( 10 )array := Copy ( arr )result := Sort ( array )fmt . Println ( "arr:\t" , arr )fmt . Println ( "result:\t" , result )}
func Sort ( arr [] int32 ) [] int32 {length := len ( arr )for i := 1 ; i < length ; i ++ {key := arr [ i ]var j intfor j = i - 1 ; j >= 0 && arr [ j ] > key ; j -- {arr [ j + 1 ] = arr [ j ]}arr [ j + 1 ] = key}return arr}
func Copy ( src [] int32 )[] int32 {length := len ( src )dest := make ([] int32 , length )for i := 0 ; i < length ; i ++ {dest [ i ] = src [ i ]}return dest}
func Random ( length int32 ) [] int32 {result := make ([] int32 , length )var i int32 = 0for i = 0 ; i < length ; i ++ {rand . Seed ( time . Nanoseconds ())result [ i ] = rand . Int31n ( 100 )}return result}
在sort中循环中判断终止条件,判断顺序是从左至右的,将 j >=0 && arr[j] > key;两个条件调换顺序会出现index outof range的错误;在打印相关函数中,输出顺序也是从左至右的,可参考上一篇《【go】++/--不是操作符》中的例子。
数组作为函数参数与c语言中类似。传入参数首地址,对整个数组都会进行相应处理。