algorithms/sorting/shell.go

32 lines
713 B
Go
Raw Normal View History

2021-12-14 14:01:44 +02:00
package sorting
2021-12-16 17:46:10 +02:00
func Shell[T any](items []T, less func(a, b T) bool) {
len := len(items)
2021-12-14 14:01:44 +02:00
gap := 1
// Calculating gap maximum value.
// This is for "Sedgewick gap sequence" variation.
// Another sequences can be used
for gap < len/3 {
gap = gap*3 + 1
}
2021-12-16 17:46:10 +02:00
// This loop needed to progressively decrease gap until simple insertion
2021-12-14 14:01:44 +02:00
// sort will be used
for gap >= 1 {
// Insertion sort loop
for i := gap; i < len; i++ {
// Instead of comparing adjacent elements we compare
// gap distance elements and swap them
2021-12-16 17:46:10 +02:00
for j := i; j >= gap && less(items[j], items[j-gap]); j -= gap {
items[j], items[j-gap] = items[j-gap], items[j]
2021-12-14 14:01:44 +02:00
}
}
// "Sedgewick gap sequence"
gap = gap / 3
}
}