希尔排序

希尔排序是插入排序的升级版,它通过将数组分成若干个子数组,对子数组进行插入排序,最后将所有子数组进行合并,得到一个有序的数组。

func TestShellSort(t *testing.T) {
    a := []int{5, 4, 3, 2, 1}
    n := len(a)
    for step := n / 2; step > 0; step = step / 2 {
        for i := step; i < len(a); i++ {
            for j := i - step; j >= 0 && a[j] > a[j+step]; j -= step {
                a[j], a[j+step] = a[j+step], a[j]
            }
        }
    }
    t.Log(a)
}

results matching ""

    No results matching ""