diff options
| author | Paul Buetow <pbuetow@mimecast.com> | 2020-08-08 16:55:09 +0100 |
|---|---|---|
| committer | Paul Buetow <pbuetow@mimecast.com> | 2020-08-08 16:55:09 +0100 |
| commit | 4a4d109bab43930299c72db1fa19b3be394791d8 (patch) | |
| tree | f3a0fd5f96cc0669aa9a44a507b7cbafb9013594 /sort/quick.go | |
| parent | 9bee249738c6bbea23a3618bd487d8d046dd2fc4 (diff) | |
better quicksort
Diffstat (limited to 'sort/quick.go')
| -rw-r--r-- | sort/quick.go | 43 |
1 files changed, 35 insertions, 8 deletions
diff --git a/sort/quick.go b/sort/quick.go index b6dd427..f3502e5 100644 --- a/sort/quick.go +++ b/sort/quick.go @@ -2,10 +2,10 @@ package sort import ( "algorithms/ds" + "math/rand" ) func Quick(a ds.ArrayList) ds.ArrayList { - Shuffle(a) quick(a) return a } @@ -22,15 +22,13 @@ func quick(a ds.ArrayList) { } func quickPartition(a ds.ArrayList) int { - i := 0 // Left scan index - j := len(a) // Right scan index + l := len(a) + i := 0 // Left scan index + j := l // Right scan index hi := j - 1 - // Median of first 3 elems is partitioning item - // This works because we randomly shuffled a in the beginning - Insertion(a[0:3]) - a.Swap(0, 1) - v := a[0] // Partitioning item + a.Swap(0, median(a, l)) + v := a[0] for { for i++; a[i] < v && i < hi; i++ { @@ -53,3 +51,32 @@ func quickPartition(a ds.ArrayList) int { // whith a[lo..j-1 <= a[j] <= a[j+1..hi] return j } + +func median(a ds.ArrayList, l int) int { + u := rand.Intn(l) + v := rand.Intn(l) + w := rand.Intn(l) + + x := a[u] + y := a[v] + z := a[w] + + if x < y { + switch { + case y < z: + return v + case x < z: + return w + default: + return u + } + } + switch { + case x < z: + return u + case y < z: + return w + default: + return v + } +} |
