From deaa4e1c33cd2c1c75f698881918688055abfa51 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Fri, 7 Aug 2020 11:14:35 +0100 Subject: add quick2 --- sort/quick2.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 sort/quick2.go (limited to 'sort/quick2.go') diff --git a/sort/quick2.go b/sort/quick2.go new file mode 100644 index 0000000..688e410 --- /dev/null +++ b/sort/quick2.go @@ -0,0 +1,43 @@ +package sort + +import ( + "algorithms/ds" +) + +// Quick2 uses a 3-way partitioning so it is more efficient +// dealing with duplicates +func Quick2(a ds.ArrayList) ds.ArrayList { + a = Shuffle(a) + quick2(a, 0, len(a)-1) + return a +} + +func quick2(a ds.ArrayList, lo, hi int) { + if hi <= lo { + return + } + + lt := lo // Lower than + i := lo + 1 // lt..i contain duplicates + gt := hi // Greater than + v := a[lo] // Partitioning item + + for i <= gt { + switch a[i].Compare(v) { + case -1: + a.Swap(lt, i) + lt++ + i++ + case 1: + a.Swap(i, gt) + gt-- + default: + // Duplicate + i++ + } + } + // Now a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi] + + quick2(a, lo, lt-1) + quick2(a, gt+1, hi) +} -- cgit v1.2.3