Anonymous user
Sorting algorithms/Comb sort: Difference between revisions
→{{header|Go}}: added more generic version
(→{{header|Go}}: added more generic version) |
|||
Line 445:
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}▼
func main() {
fmt.Println("before:", a)
combSort(a)
fmt.Println("after: ", a)
}
func combSort(a []int) {
if len(a) < 2 {
return
Line 462 ⟶ 461:
gap = gap * 4 / 5
}
for i := 0; ; {
if a[i] > a[i+gap] {
Line 470 ⟶ 469:
i++
if i+gap >= len(a) {
break
}
}
if gap == 1 && !swapped {
break
}
}
}</lang>
More generic version that sorts anything that implements <code>sort.Interface</code>:
<lang go>package main
import (
"sort"
"fmt"
)
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
combSort(sort.IntArray(a))
fmt.Println("after: ", a)
}
func combSort(a sort.Interface) {
if a.Len() < 2 {
return
}
for gap := a.Len(); ; {
if gap > 1 {
gap = gap * 4 / 5
}
swapped := false
for i := 0; ; {
if a.Less(i+gap, i) {
a.Swap(i, i+gap)
swapped = true
}
i++
if i+gap >= a.Len() {
break
}
|