diff options
| author | Paul Buetow <pbuetow@mimecast.com> | 2020-08-07 11:14:35 +0100 |
|---|---|---|
| committer | Paul Buetow <pbuetow@mimecast.com> | 2020-08-07 11:14:35 +0100 |
| commit | deaa4e1c33cd2c1c75f698881918688055abfa51 (patch) | |
| tree | c6a82fec9cc3030f169d0b4441a8c63dd6bd1ea1 /sort/quick2.go | |
| parent | d4c15be3268ee675b0d5853a8ffdb6c4c92585e7 (diff) | |
add quick2
Diffstat (limited to 'sort/quick2.go')
| -rw-r--r-- | sort/quick2.go | 43 |
1 files changed, 43 insertions, 0 deletions
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) +} |
