用GO语言 实现 希尔排序
时间: 2023-07-23 19:03:58 浏览: 97
希尔排序是一种插入排序的改进版,它通过将待排序元素按照一定的间隔分组,对每组使用插入排序,然后逐步缩小间隔,直到间隔为1,最后使用插入排序完成排序。以下是用GO语言实现希尔排序的代码:
```go
func shellSort(arr []int) {
n := len(arr)
// 初始化间隔为n/2
gap := n / 2
for gap > 0 {
// 对各个分组进行插入排序
for i := gap; i < n; i++ {
temp := arr[i]
j := i
for j >= gap && arr[j-gap] > temp {
arr[j] = arr[j-gap]
j -= gap
}
arr[j] = temp
}
// 缩小间隔
gap /= 2
}
}
```
我们可以使用以下代码来测试希尔排序的实现:
```go
func main() {
arr := []int{5, 3, 8, 4, 2}
shellSort(arr)
fmt.Println(arr)
}
```
输出结果为:`[2 3 4 5 8]`,表示排序成功。
阅读全文
相关推荐
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)