Sorting algorithms/Comb sort: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: added more generic version)
Line 445: Line 445:


import "fmt"
import "fmt"

var a = []int{170, 45, 75, -90, -802, 24, 2, 66}


func main() {
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
fmt.Println("before:", a)
combSort()
combSort(a)
fmt.Println("after: ", a)
fmt.Println("after: ", a)
}
}


func combSort() {
func combSort(a []int) {
if len(a) < 2 {
if len(a) < 2 {
return
return
Line 462: Line 461:
gap = gap * 4 / 5
gap = gap * 4 / 5
}
}
var swapped bool
swapped := false
for i := 0; ; {
for i := 0; ; {
if a[i] > a[i+gap] {
if a[i] > a[i+gap] {
Line 470: Line 469:
i++
i++
if i+gap >= len(a) {
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
break
}
}