TL;DR -> Do this over and over: Pick pivot, partition, sort.
C-The C version is quite standard, implementing an in-place quicksortwhich is not only fast, but also saves on memory.While pivot selection is apparently a hot topic in some circles,this simple version doesn't bother with any fancy work and simplytakes the middle element (of each subset) as the pivot. One could be evenlazier and skip this entirely, taking the first element as the pivot, butif your list is sorted perfectly backwards and sufficiently long enough,you could blow the stack.-- I've included a short unit test for the C version as well, so feelfree to compile that in your spare time.PYTHON------Nearly identical to the C version, and a lot shorter.This implementation does its best not to inefficiently throw memory around,and (in theory) is an in-place sort.As a bonus from using Python, we can specify default values in qsort()'sfunction definition. Take a look! This allows us to simply pass somethinglike: qsort([4,5,2]) and everything will be taken care of.(Recall the C version where we had to pass the starting lower and upperbound values right off the bat)We also chose a different method of pivot selection. Here, we tookthree values, the lower, upper, and middle, sorted them, then chose thepivot position to be element number corresponding to the middle value(essentially the average). This ensures that the pivot will never be anoutlier, needlessly extending the stack and the amount of work that needsto be done. A combination of several built-in functions takes care ofthis work nicely for us, as can be seen in the get_pivot_pos() function.HASKELL-------Ahhh filters and lazy evaluation. This solution is obviously the cleanestout of the three. The pivot here is the same as the C version, simplychosen as the middle element of the set. This can easily be made a one-linerif you don't much care for names and neat-looking code.
No comments:
Post a Comment