Blame view
quicksort.go
1.06 KB
84543a02b quicksort |
1 2 3 4 5 |
package webutility type QSortDirection int const ( |
b80ee4b2b new stuff |
6 7 |
QSortAscending QSortDirection = iota QSortDescending |
84543a02b quicksort |
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
) // QuickSortable is an interface for quicksorting slices. type QuickSortable interface { Swap(i, j int) Compare(i, j int) int Len() int } // Quicksort quicksorts que. func Quicksort(que QuickSortable, low, high int, dir QSortDirection) { if low >= high { return } if dir != QSortAscending && dir != QSortDescending { return } index := partition(que, low, high, dir) Quicksort(que, low, index-1, dir) Quicksort(que, index+1, high, dir) } func partition(que QuickSortable, low, high int, dir QSortDirection) int { |
b80ee4b2b new stuff |
33 34 35 36 37 38 39 40 |
swap := 0 // -1 -> i > j // 1 -> i < j if dir == QSortDescending { swap = -1 } else { swap = 1 } |
84543a02b quicksort |
41 42 |
i := low - 1 for j := low; j <= high-1; j++ { |
b80ee4b2b new stuff |
43 44 45 |
if que.Compare(j, high) == swap { i++ que.Swap(i, j) |
84543a02b quicksort |
46 |
} |
b80ee4b2b new stuff |
47 |
continue |
84543a02b quicksort |
48 49 50 51 |
} que.Swap(i+1, high) return i + 1 } |
62a0d7a8a minor changes |
52 53 54 55 56 57 58 59 60 61 |
func BubbleSort(arr []int64) { for i := 0; i < len(arr)-1; i++ { for j := i; j < len(arr); j++ { if arr[i] > arr[j] { arr[i], arr[j] = arr[j], arr[i] } } } } |