go实现希尔排序算法

前面我们详细讲解了希尔排序算法,现在我们直接上go代码

package main

import "fmt"
//希尔排序
func shellSort(theArray []int) []int {
	d_value := len(theArray) / 2
	for d_value > 0 {
		for i := 0; i < len(theArray); i++{
			j := i
			for ((j-d_value >= 0) && (theArray[j] < theArray[j - d_value])) {
				theArray[j], theArray[j - d_value] = theArray[j - d_value], theArray[j]
				j -= d_value;
			}
		}
		d_value /= 2
		fmt.Println(theArray)
	}
	return theArray
}

func main() {
	var theArray = []int{1,0,2,10,9,70,5,6,3}
	fmt.Print("排序前")
	fmt.Println(theArray)
	fmt.Print("排序后")
	fmt.Println(shellSort(theArray))
}

我们运行下代码

排序前[1 0 2 10 9 70 5 6 3]
排序后[1 0 2 6 3 70 5 10 9]
[1 0 2 6 3 10 5 70 9]
[0 1 2 3 5 6 9 10 70]
[0 1 2 3 5 6 9 10 70]

符合预期

你可能感兴趣的:(算法与数据结构,go实现希尔排序算法,go算法实现,数据结构和算法,算法,go,算法)