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 {
for i := 0; i < len(slice); i++ {
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)
}
}
@@ -57,6 +58,30 @@ func SelectionSort[T any](slice []T, comparator lancetconstraints.Comparator) []
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 {
// if low < high {
// var p int