views:

940

answers:

3

What is QuickSort with a 3-way partition?

+6  A: 

http://www.sorting-algorithms.com/static/QuicksortIsOptimal.pdf

See also:

http://www.sorting-algorithms.com/quick-sort-3-way

I thought the interview question version was also interesting. It asks, are there four partition versions of quicksort...

altCognito
+12  A: 

Picture an array:

3, 5, 2, 7, 6, 4, 2, 8, 8, 9, 0

A two partition Quick Sort would pick a value, say 4, and put every element greater than 4 on one side of the array and every element less than 4 on the other side. Like so:

3, 2, 0, 2, 4, | 8, 7, 8, 9, 6, 5

A three partition Quick Sort would pick two values to partition on and split the array up that way. Lets choose 4 and 7:

3, 2, 0, 2, | 4, 6, 5, 7, | 8, 8, 9

It is just a slight variation on the regular quick sort.

You continue partitioning each partition until the array is sorted. The runtime is technically log3(n) which varies ever so slightly from regular quicksort's log2(n).

jjnguy
+1 for the concise explanation.
altCognito
Thanks !
jjnguy
Now the interesting question is: "Under what conditions is a n-way QS better than a m-way QS?"
dmckee
I suppose different partition amounts can work better in different cases. But 2 way seems to work well enough for me.
jjnguy
+4  A: 

if you really grind out the math using Akra-Bazzi formula leaving the number of partitions as a parameter, and then optimize over that parameter, you'll find that e ( =2.718...) partitions gives the fastest performance. in practice, however, our language constructs, cpus, etc are all optimized for binary operations so the standard partitioning to two sets will be fastest.

Autoplectic
Ah! Just what I was looking for. Thanks.
dmckee