本文主要是介绍go实现耐心排序算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前面我们讲解了耐心排序算法,今天我们来看一下代码的实现,直接上代码
package mainimport ("fmt"
)//耐心排序func patienceSort(theArray[] int)[]int {newList := make([][]int, 0)for i := 0; i < len(theArray); i++ {bucketList := make([]int, 0)if (i == 0) {bucketList = append(bucketList, theArray[i])newList = append(newList, bucketList)} else {isOk := false;for j := 0; j < len(newList); j++ {if theArray[i] < newList[j][0] {newList[j] = append(newList[j][:0], append([]int{theArray[i]}, newList[j][0:]...)...)isOk = true;break}}if (!isOk) {bucketList = append(bucketList, theArray[i])newList = append(newList, bucketList)}}}oklist := make([]int, 0)for m :=0; m < len(newList); m++{for n:=0; n < len(newList[m]); n++{oklist = append(oklist, newList[m][n])}}//fmt.Println(oklist)//插入排序theLen := len(oklist)var i intfor i < theLen{var tmp = oklist[i]for m:=i-1; m>=0 && oklist[m]>tmp; m--{oklist[m],oklist[m+1] = oklist[m+1],oklist[m]//更简单的值互换方式}i++}return oklist
}
func main() {theArray := []int{6, 4, 5, 1, 8, 7, 2, 3}fmt.Print("排序前")fmt.Println(theArray)fmt.Print("排序后")fmt.Println(patienceSort(theArray))
}
运行结果如下
排序前[6 4 5 1 8 7 2 3]
排序后[1 2 3 4 5 6 7 8]
符合预期
这篇关于go实现耐心排序算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!