From 84543a02b292c5be658f2b191377091affc4ef3d Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Tue, 10 Sep 2019 15:43:17 +0200 Subject: [PATCH] quicksort --- quicksort.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 quicksort.go diff --git a/quicksort.go b/quicksort.go new file mode 100644 index 0000000..ba627fb --- /dev/null +++ b/quicksort.go @@ -0,0 +1,49 @@ +package webutility + +type QSortDirection int + +const ( + QSortAscending = 0 + QSortDescending = 1 +) + +// 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 { + i := low - 1 + for j := low; j <= high-1; j++ { + if dir == QSortAscending { + if que.Compare(j, high) == -1 { + i++ + que.Swap(i, j) + } + } else if dir == QSortDescending { + if que.Compare(j, high) == 1 { + i++ + que.Swap(i, j) + } + } + } + que.Swap(i+1, high) + return i + 1 +} -- 1.8.1.2