1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add ShellSort

This commit is contained in:
dudaodong
2022-01-14 18:17:46 +08:00
parent d491bea263
commit 43e0ca7edf
2 changed files with 39 additions and 1 deletions

View File

@@ -10,7 +10,8 @@ import "github.com/duke-git/lancet/lancetconstraints"
func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) []T { func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) []T {
for i := 0; i < len(slice); i++ { for i := 0; i < len(slice); i++ {
for j := 0; j < len(slice)-1-i; j++ { for j := 0; j < len(slice)-1-i; j++ {
if comparator.Compare(slice[j], slice[j+1]) == 1 { isCurrGreatThanNext := comparator.Compare(slice[j], slice[j+1]) == 1
if isCurrGreatThanNext {
swap(slice, j, j+1) swap(slice, j, j+1)
} }
} }
@@ -57,6 +58,30 @@ func SelectionSort[T any](slice []T, comparator lancetconstraints.Comparator) []
return slice return slice
} }
// ShellSort shell sort slice.
func ShellSort[T any](slice []T, comparator lancetconstraints.Comparator) []T {
size := len(slice)
if size <= 1 {
return slice
}
gap := 1
for gap < size/3 {
gap = 3*gap + 1
}
for gap >= 1 {
for i := gap; i < size; i++ {
for j := i; j >= gap && comparator.Compare(slice[j], slice[j-gap]) == -1; j -= gap {
swap(slice, j, j-gap)
}
}
gap /= 3
}
return slice
}
// func QuickSort[T comparable](slice []T, low, high int) []T { // func QuickSort[T comparable](slice []T, low, high int) []T {
// if low < high { // if low < high {
// var p int // var p int

View File

@@ -110,3 +110,16 @@ func TestSelectionSort(t *testing.T) {
asssert.Equal(expected, actual) asssert.Equal(expected, actual)
} }
func TestShellSort(t *testing.T) {
asssert := internal.NewAssert(t, "TestShellSort")
comparator := &peopleAageComparator{}
sortedPeopleByAge := ShellSort(peoples, comparator)
t.Log(sortedPeopleByAge)
expected := "[{d 8} {b 10} {c 17} {a 20} {e 28}]"
actual := fmt.Sprintf("%v", sortedPeopleByAge)
asssert.Equal(expected, actual)
}