Advertisement
Ladies_Man

#SORT__Quick sort GO

Mar 5th, 2014
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.97 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func partition(less func(i, j int) bool, swap func(i, j int), low, high int) int {
  6.         i, j := low, low
  7.  
  8.     for j < high {
  9.         if less(j, high) {
  10.             swap(i, j)
  11.             i++
  12.         }
  13.         j++
  14.     }
  15.     swap(i, high)
  16.     return i
  17. }
  18.  
  19. func qsort(n int, less func(i, j int) bool, swap func(i, j int)) {
  20.     var qsortrec func(less func(i, j int) bool, swap func(i, j int), low int, high int)
  21.     qsortrec = func(less func(i, j int) bool, swap func(i, j int), low int, high int) {
  22.         if low < high {
  23.             q := partition(less, swap, low, high)
  24.             qsortrec(less, swap, low, q - 1)
  25.             qsortrec(less, swap, q + 1, high)
  26.         }
  27.     }
  28.     qsortrec(less, swap, 0, n - 1)
  29. }
  30.  
  31. func main() {
  32.     var i, n, b int
  33.     fmt.Scanf("%d", &n)
  34.     a := make([]int, 0, n)
  35.  
  36.     for i < n {
  37.         fmt.Scanf("%d", &b)
  38.         a = append(a, b)
  39.         i++
  40.     }
  41.  
  42.     qsort(len(a), func(i, j int) bool { return a[i] < a[j] }, func(i, j int) { a[i], a[j] = a[j], a[i] },)
  43.  
  44.     for _, b := range a {
  45.         fmt.Printf("%d ", b)
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement