Commit 84543a02b292c5be658f2b191377091affc4ef3d

Authored by Marko Tikvić
1 parent 69178b8246
Exists in master

quicksort

Showing 1 changed file with 49 additions and 0 deletions   Show diff stats
... ... @@ -0,0 +1,49 @@
  1 +package webutility
  2 +
  3 +type QSortDirection int
  4 +
  5 +const (
  6 + QSortAscending = 0
  7 + QSortDescending = 1
  8 +)
  9 +
  10 +// QuickSortable is an interface for quicksorting slices.
  11 +type QuickSortable interface {
  12 + Swap(i, j int)
  13 + Compare(i, j int) int
  14 + Len() int
  15 +}
  16 +
  17 +// Quicksort quicksorts que.
  18 +func Quicksort(que QuickSortable, low, high int, dir QSortDirection) {
  19 + if low >= high {
  20 + return
  21 + }
  22 +
  23 + if dir != QSortAscending && dir != QSortDescending {
  24 + return
  25 + }
  26 +
  27 + index := partition(que, low, high, dir)
  28 + Quicksort(que, low, index-1, dir)
  29 + Quicksort(que, index+1, high, dir)
  30 +}
  31 +
  32 +func partition(que QuickSortable, low, high int, dir QSortDirection) int {
  33 + i := low - 1
  34 + for j := low; j <= high-1; j++ {
  35 + if dir == QSortAscending {
  36 + if que.Compare(j, high) == -1 {
  37 + i++
  38 + que.Swap(i, j)
  39 + }
  40 + } else if dir == QSortDescending {
  41 + if que.Compare(j, high) == 1 {
  42 + i++
  43 + que.Swap(i, j)
  44 + }
  45 + }
  46 + }
  47 + que.Swap(i+1, high)
  48 + return i + 1
  49 +}
... ...