Skip to content

Commit 29f8525

Browse files
committed
add shell sort
1 parent d52b482 commit 29f8525

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

shell_sort.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,19 @@ package algorithm
88
// 3.每趟排序,根据对应的增量 ti,将待排序列分割成若干长度为 m 的子序列,分别对各子表进行直接插入排序。
99
// 仅增量因子为 1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。
1010
func ShellSort(arr []int) []int {
11+
length := len(arr)
12+
gap := length / 2
13+
for gap > 0 {
14+
for i := gap; i < length; i++ {
15+
temp := arr[i]
16+
j := i - gap
17+
for j >= 0 && arr[j] > temp {
18+
arr[j+gap] = arr[j]
19+
j -= gap
20+
}
21+
arr[j+gap] = temp
22+
}
23+
gap = gap / 2
24+
}
1125
return arr
1226
}

shell_sort_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package algorithm
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestShellSort(t *testing.T) {
11+
arr := []int{3, 2, 0, 5, 10, 1, 13}
12+
arrSort := ShellSort(arr)
13+
fmt.Printf("arr after sored: %v\n", arrSort)
14+
assert.Equal(t, 10, arrSort[5])
15+
assert.Equal(t, 5, arrSort[4])
16+
}

0 commit comments

Comments
 (0)