Created
June 12, 2010 19:56
-
-
Save napsy/436019 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, size int) []Sortable { | |
if size <= 1 { | |
return table | |
} | |
half := size / 2 | |
left := make([]Sortable, len(table)) | |
right := make([]Sortable, len(table)) | |
sorted := make([]Sortable, len(table)) | |
pivot := table[half] | |
i := 0 | |
j := 0 | |
for idx, item := range table[0:size] { | |
if idx == half { | |
continue | |
} | |
if item.Less(pivot) { | |
left[i] = item | |
i++ | |
} else { | |
right[j] = item | |
j++ | |
} | |
} | |
copy(sorted, qsort(left, i)) | |
sorted[i] = pivot | |
copy(sorted[i+1:size], qsort(right, j)) | |
return sorted | |
} | |
func main() { | |
var p []Sortable = []Sortable{Person{4, 5, "df"}, | |
Person{6, 3, "fd"}, | |
Person{3, 3, "fd"}, | |
Person{2, 3, "fd"}, | |
Person{8, 3, "fd"}} | |
sorted := qsort(p, len(p)) | |
for _, i := range sorted { | |
fmt.Printf("%d ", i.(Person).age) | |
} | |
fmt.Printf("\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment