Monday, April 22, 2013

Coding Practice: Quicksort

I've mentioned sorting algorithms several times in the past, with a specific focus on Mergesort. Today's article introduces Quicksort, another common sorting algorithm. The article starts with an intuitive, non-technical description. Next, the article presents the C code and a hand-wavy theoretical analysis of its computational complexity, backed by a pinch of practical results. The article concludes with a comparison with the Mergesort algorithm.

Intuitive Description

The most intuitive description of the Quicksort algorithm is credited to its inventor, Tony Hoare:
"Just grab a thing and compare the other things with it."
The trick is that Quicksort "grabs" and "compares" intelligently, avoiding unnecessary comparisons and allowing it to sort a collection in logarithmic time. Specifically, this is achieved by partitioning the collection around the thing we just grabbed (called the "pivot") into two smaller collections. Everything smaller than or equal to the pivot goes into the left sub-collection, and everything else goes into the right sub-collection. The two sub-collections can then be Quicksort-ed independently, recursively. The recursion terminates when the sub-collections contain less than two elements.

Code and Analysis of Computational Complexity

The code for Quicksort is fairly straightforward:

Most of the work is performed in the partition method, which can be implemented in-place.

The computational complexity of Quicksort depends on the selection of the pivot element. In the best case, the selected pivot is the median of the collection and the partition step divides the collection into two smaller collections of identical size. Since the size of the sorted collection is halved at each step of the recursion, the best case complexity of Quicksort is $O(N \log N)$. In the worst case, the selected pivot is the minimum or maximum of the collection, and the partition step achieves very little. The worst case complexity is $O(N^2)$.

There are several ways to select the pivot element, the simplest being selecting the first, last or middle element of the collection. Since selecting the first or last element can lead to worst-case performance if the array is already sorted, selecting the middle element is the better option of the three.

The effect of pivot selection on the complexity of Quicksort can be observed empirically, by counting the number of comparisons for three different types of input: random, sorted and uniform; and for three different pivot selection methods: first, last and middle. Here are some results (sorting 100 input elements, showing the number of comparisons first, last, middle selection modes, respectively):
  • random (mean over 100 runs): 713.28, 715.17, 713.25 
  • sorted: 1001, 1001, 543 
  • same: 1001, 1001, 1001
The above results support what is already well-known: merge sort performs worst when given sorted and uniform input. The former can be dealt with by selecting the middle element as the pivot (or even randomizing the pivot selection). The latter can be dealt with by checking for uniform input prior to sorting, which will take O(N).

To obtain these results, I used GDB (to set breakpoints and count the number of hits), Python (to generate the input) and bash (to tie everything together). The entire code for reproducing these results is here.

Comparison with Mergesort

Mergesort and Quicksort are both divide-and-conquer sorting algorithms. They work by first dividing the input data into parts and then recursively processing each part separately. However, there are significant differences between them.
  1. First, Quicksort does all of its work in the divide (partition) step. The conquer step is trivial, since after recursion is complete, the array is completely sorted. In contrast, Mergesort does very little work in the divide step, and does most of its work after the recursion is complete.
  2. Second, the algorithms have different computational complexity: Mergesort is consistent $O(N \log N)$, Quicksort is $O(N \log N)$, $O(N \log N)$ and $O(N^2)$ in the best, average and worst-case, respectively.
  3. Third, the algorithms have different space complexity: unlike Mergesort, Quicksort's partition step can be implemented in-place without significant impact on complexity.
  4. Fourth, unlike Mergesort, Quicksort is not a stable sorting algorithm, since the partition step reorders elements. Stable implementations of Quicksort do exist, but are not in-place.
  5. Finally, Mergesort is easier to parallelize than Quicksort, since the divide step is simpler with the former.


If you're one of the chosen few that managed to soldier on through the entire article, give yourself a pat on the back. Thanks for reading the entire thing. Please reward yourself with a refreshing chuckle at this sorting-related comic:

Monday, April 8, 2013

An (unexpected) defense of Microsoft Store...

I know I had a lot of fun bashing Microsoft and their Online Store last week, but being a fair and level-minded individual, I feel that I do need to say some things in their defense.

While they failed to obtain my business for the University 365 offer (a blunder that they will surely regret for decades), a quick read of the MS Office license revealed that, as a proud owner of the Home and Student version, I can install it on one more PC.  Which is what I promptly did (can't beat free!).

Unfortunately, the smooth sailing ended here.  In blind defiance of the above-mentioned license, the installed program refused to authenticate, and threatened to disable itself within a month if I did not provide it with a new license key, which, as we all know, costs bags of money.  Having read the The License, I was fully confident in my self-righteousness.  There was no way I was going to pay for something that was already mine.  I did the unthinkable.  I picked up my phone and called the Verification Hotline.

The Verification Hotline is the last resort for people that want to authenticate a Microsoft product, but for one reason or another can't do so over the Internet.  It was well after 7pm when I called, so I half-expected to be kindly asked to call back the next day.  Fortunately, these expectations were misplaced, and I was treated to a warming chat with... a computer.  To proceed with verification, you need to enter something like 64 digits (through the keypad!) to identify your install.  It's difficult to convey the rush of adrenaline as you power towards the last couple of digits.  I've never diffused a bomb, or issued a launch code for an ICBM, but I guess those experiences would come pretty close.

After all that, I got through to an operator.  Finally, a chance to plead my case...  in Japanese.  Great.  After a long and thorough discussion about when and how I installed The Product, the operator agreed to activate my installation.  To do that, I had to enter another missile launch code into my Office install, as she was reading it out.  Another 64 digits or so, and my efforts would finally bear fruit.

My call got cut off after 10 digits.  Game over, man!

Unable to control the fury, I redialed the number, and mashed the keypad until an option to talk to an operator was presented.  I had naively expected that somehow, the person I was talking to before would be there, and we could pick up where we left off...  Alas, that was not to be.  The voice on the other side of the phone was cold and distant.  "I'm afraid you'll have to start again...", she said apologetically.

Like I mentioned earlier, I'm a fairly persistent guy when I need to be.  I persevered.  Entering the 64-digit launch code a second time through was nowhere as painful as the first.  I had the thought that by the time I'd have gone through the process another 3 or 4 times, I'd have the whole thing memorized.  It's really no big deal -- back in the good old days of Windows 95, I reinstalled the O/S so often I had the whole product key committed to memory.

While what I've written so far doesn't really do much in defense of the Microsoft Store, there really is a happy ending to all this.  After I entered my launch code a second time, I didn't have to jump through any more hoops.  The kind soul I spoke to the first time through pre-recorded the authorization code for me, and all I had to do was punch that into my Office install.  All done!  And it only took half an hour...

Furthermore, I had to recently stumble into The Store on an unrelated issue.  I was surprised to see something that I don't recall seeing before -- a live chat option.  You click on that, and get to talk to a real person.  Straightaway.  It's brilliant!  If only that was there a week ago -- I wouldn't have had to rant.  Oh well.  Better out than in, they say.

Thursday, April 4, 2013

The Decimator, 2.0

A little while ago, I wrote about the woes of dealing with numbers in Japanese notation.  Since I never let an opportunity to procrastinate to pass me by, I also posted a brief JavaScript (The Decimator™) to help deal with the confusion.  A friend of mine pointed out that it doesn't help with some use cases, such as 千5百万 (that's 15 million, but you knew that, right?).  And thus another opportunity to procrastinate presented itself, and now, I give you the Decimator™, 2.0:

It accepts free text input, and handles both traditional (Kanji only) and mixed (Arabic numerals plus Kanji) numbers.  Feel free to give it a whirl.