Skip to content

Instantly share code, notes, and snippets.

@napsy
Created June 12, 2010 18:13
Show Gist options
  • Save napsy/435955 to your computer and use it in GitHub Desktop.
Save napsy/435955 to your computer and use it in GitHub Desktop.
package main
import "fmt"
type Sortable interface {
Less(b Sortable) bool
}
type Person struct {
age, height int
fullname string
}
func (a Person) Less(b Sortable) bool {
if a.age < b.(Person).age {
return true
}
return false
}
func qsort(table []Sortable) []Sortable {
half := len(table) / 2
left := make([]Sortable, len(table))
right := make([]Sortable, len(table))
sorted := make([]Sortable, len(table))
pivot := table[half]
i := 0
j := 0
for _, item := range table {
if item.Less(pivot) {
left[i] = item
i++
} else {
right[j] = item
j++
}
}
copy(sorted, qsort(left))
sorted[len(sorted)] = pivot
copy(sorted[len(left)+1:len(table)], qsort(right))
return sorted
}
func main() {
var p []Person = []Person{Person{4, 5, "df"},
Person{6, 3, "fd"}}
sorted := qsort([]Sortable(p))
for _, i := range sorted {
fmt.Printf("%d ", i.(Person).age)
}
}
// I get : sort.go:49: cannot convert p (type []Person) to type []Sortable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment