r/dailyprogrammer • u/Elite6809 1 1 • Aug 25 '14
[8/25/2014] Challenge #177 [Easy] Quicksort
(Easy): Quicksort
On a daily basis we take advantage of the power of a language's standard library. One of the common functions within such libraries is for sorting sets of data. This saves you some time so you don't have to write it yourself. But what about the occasions when you don't have a standard library?
You might be tempted to implement a sorting algorithm such as insertion sort or bubble sort. However, while being simple, they are slow and inefficient, with O(n2) running time - meaning on average, doubling the length of the list to be sorted increases the running time by a factor of four. Now this can be useful sometimes, eg. if you need to write a tiny program, like on an Arduino. However, in the vast majority of cases this is bad.
Luckily there are alternate methods of sorting. Today, we will be looking at a method known as quicksort. This involves:
- Start with the whole list.
- Pick a random value from the list - it does not have to be from the middle. This will be our pivot.
- Reorder the list, moving (in no particular order) everything that is smaller than the pivot to the left of it and everything that's greater than the pivot to the right of it.
Now, the list to the left of, not including, the pivot is known as list S, and the list to the right of, not including, the pivot is known as list G.
S and G don't have to be created in order, just so long as they are all smaller or greater than the pivot respectively. - Now repeat step 2 onward for lists S and G. If the list only contains zero or one items, you can stop, as it's by default sorted. If either only contains 2 items, it might make it quicker to just compare and swap if necessary instead of doing the whole sorting procedure.
You challenge today is, given an arbitrarily long list of real numbers, sort them using your own, non-library version of quicksort.
Formal Inputs & Outputs
Input
You will take an integer N. This will be the size of our list. You will then take a further N real (ie. floating/decimal) numbers on separate lines. This is the content of our list.
Output
Output the list after sorting with your version of quicksort. This should also be on separate line.
Notes
If you have not already learned it, this is a golden opportunity to use and learn recursion. Remember, using your language's built-in sorting implementation defeats the purpose of this exercise, and if you do post such a solution, prepare for a sarcastic response.
12
u/threeifbywhiskey 0 1 Aug 25 '14
This Ruby solution is, in my opinion, almost as pretty as the canonical Haskell one:
10
u/wadehn Aug 25 '14 edited Aug 26 '14
C++: Since this challenge is pretty easy, I also implemented some of the improvements you'd have to consider in practice:
Edit:
Caveat:
The resulting code is certainly not beautiful, but quite practical (Also contains code for benchmarking):
Benchmark with 10 million elements randomly chosen from {0, ..., 100000} on my machine:
My code is pretty close to
std::sort(nice!, but only for this best case).7
u/jeaton Aug 25 '14 edited Aug 25 '14
This is pretty much a copy and paste from my GitHub repository of random sorting algorithms. This is a version that doesn't require constructing multiple arrays.
JavaScript:
What's interesting is that this quicksort implementation seems to be faster than JavaScript's built-in sorting algorithm (assuming you only want to sort arrays of numbers). It gets quite a bit slower than JavaScript's function when you add a comparison function. EDIT: Looks like this function may only be faster using Chrome's V8 JavaScript engine. It looks like this isn't the case in other browsers.
EDIT:
C++:
Python:
7
u/basic_bgnr Aug 25 '14 edited Aug 26 '14
I'm learning haskell and the whole reason behind learning was qsort. It cannot be more simple than this. it doesn't uses random pivot point.(Random number generation in haskell is pretty complicated than other language and i'm just starting).
edit: removed redundant code
6
u/crossed_xd Aug 25 '14 edited Aug 25 '14
My solution in Java. I used Lists rather than arrays because they're generally easier to work with, and don't really impede performance that much (that I can tell, though my machine's slow to begin with).
Any feedback is appreciated.
Edit: tweaked an if() statement following the advice of /u/Quadrophenic
Note: The issue involving Lists containing the exact same value caught me off-guard initially (stack overflow errors, lol), but I managed to resolve it by splitting all pivot values off into their own List, as you'll see in the code.
5
u/Quadrophenic Aug 25 '14 edited Aug 25 '14
PHP
My aim was to make my code as simple and expressive as possible. This does cause this to be a memory hog, since the sort happens in sub-lists instead of in place (uses O(n) memory in addition to the list, instead of O(log(n)), which will be optimal and is what /u/jeaton does).
For funsies, let's verify empyrically that this is O(n*log(n)):
Output:
We expect the output here to be constant, so this looks about right.
Finally, an alternate version that does not use the array_merge built-in (I realize it isn't a sorting algorithm, but it does help with the combining step of our divide and conquer)
5
u/MaximaxII Aug 25 '14
Here we go! A recursive Python solution that supports floats, integers and powers of 10 (29e12, for instance).
Challenge #177 Easy - Python 3.4
5
u/[deleted] Aug 25 '14 edited Aug 26 '14
Prolog. Using DCGs (Definite Clause Grammars) and the SWI-Prolog standard library predicate
partition/4(which separates, but doesn't sort), we get a piece of surprisingly elegant and succinct code:At least, I was surprised at how pretty it looks! Concision isn't always Prolog's strong point. (It's nearly a perfect analog to the Haskell code, but relational programming leads us to use a single call to get both the
SandG. A Haskell function with multiple returns in a tuple, e.g.[a] -> (a -> a -> bool) -> ([a], [a])(is this right?) could be used to the same effect.)This code partitions the list according to the predicate
@>/2, which compares the elements according Prolog's standard order of terms: "Variables < Numbers < Strings < Atoms < Compound Terms". As a result, this is a general quicksort algorithm, which will sort a list of any comparable terms, not just numbers. E.g.,The rest of the program, satisfying the input and output criteria of the assignment, runs thus:
Usage:
The
.operator is the standard Prolog statement terminator. It's used in these inputs so I could save myself the task of converting to and from strings or character codes, as the latter wasn't required by the assignment.The quicksort algorithm I used is basically the same as the one used in an example on the Prolog wikipedia page. Except that the latter also details implementation of the
partition/4predicate.4
u/skeeto -9 8 Aug 25 '14 edited Aug 25 '14
C99, as a possible implementation of C's
qsort()since it has the same function signature. My version is an unstable sort, but I think it could be stable with just a few (performance reducing) modifications.This wasn't mentioned in the challenge text, but quicksort is an in-place sort algorithm. If you're allocating a new array, like many of you have, what you've probably implemented instead is tree sort.
4
u/hutsboR 3 0 Aug 25 '14
Dart:
It isn't in place.
1
u/ddsnowboard Aug 30 '14
Python. Should I feel like a simpleton for using Python and not something more difficult? I dunno... Anyway, criticism appreciated.
3
u/DeaderThanElvis Aug 25 '14
My Java attempt in 5 minutes. Really surprised myself that the code ran correctly at the first attempt. Also, I'm sorry I didn't implement it using the formal input/output guidelines.
3
u/sadjava Aug 25 '14
A Java solution using generic lists. I've supplied two different sort methods. One assumes that the list is in the worst condition of a quick sort, where the list is almost sorted and would run in O(n2 ). The other assumes the list is randomized. And as a note, I used Comparators since, at least in some of my programs, I need to sort something and go "oh s**t, it doesn't extend Comparable". All bets are off for Linked Lists; I don't want to even think about how brutal those will be.
3
u/CatatonicMan Aug 26 '14 edited Aug 26 '14
Quick solution with Python. The quicksort part is short; the rest is input handling. It would probably be faster if I did the binning all in one pass, but whatever. It's also not sorting in place.
Edit: I went ahead and made an in-place version of quicksort, since it seems more in line with what the question asked.
2
u/Godspiral 3 3 Aug 25 '14 edited Aug 25 '14
From J's wikipedia page http://en.wikipedia.org/wiki/J_(programming_language)
quicksort 5.1 5.2 4.3 3.4 8.5 1.6 2.7 4.8 8.9 9
1.6 2.7 3.4 4.3 4.8 5.1 5.2 8.5 8.9 9
recursion operator is $:
step 2: pick a random number from 0 to length and select from list. Could be clearer with: (] {~ ?@#)
and whole expression clearer as:
the reason that is clearer is that [ normally refers to the left argument, which does not explicitly get set in quicksort. The shorter original statement places the the right (only) argument as an implicit left argument by having only 2 verbs in its tacit form(s). I find it good clarity practice to add the unnecessary ] in the left part of the trains.
S: ($:@(<#[)
G: $:@(>#[)
(<#[) -- < will create a boolean list based on whether items in list are smaller than pivot item. (boolist # [) selects items where boolist is 1. $@: will apply whole expression to that selection.
(=#[) similarly selects items that are equal to pivot point. , just concatenates all the results.
10m random bytes in 3.24 seconds
timespacex 'quicksort Randdata'
3.24316 3.83266e8
though builtin sort much faster:
timespacex '/:~ Randdata'
0.100827 1.34224e8
2
u/datgohan Aug 25 '14
PHP used for this, my first attempt at writing a quick sort algorithm. Comments and advice are very welcome as I tried to get this working with recursion which is a rarity for me! :)
2
u/jnazario 2 0 Aug 25 '14 edited Aug 26 '14
F#, not in place EDITED TO ADD
usage
2
u/[deleted] Aug 25 '14
My solution in D
Output:
2
u/Sawny Aug 25 '14
Haskell:
2
u/shandow0 Aug 25 '14 edited Aug 25 '14
Here's my attempt in C#:
2
u/thestoicattack Aug 25 '14
Ada:
generic specification:
implementation:
main program:
2
u/regul Aug 25 '14 edited Aug 25 '14
Go:
I was a bit freaked out about creating and extending so many slices, but Go's slices are meant to be flexible. In fact, I was looking into converting this to use Lists, but the general consensus seems to be that Go's slices are better than the linked-list implementation in almost every respect.
Edit: Fixed.
2
u/easher1 Aug 25 '14 edited Aug 25 '14
QuickSort implemented for a Generic Type, with a median of 3 partitioning strategy. Java 7
2
u/mtko Aug 25 '14 edited Aug 25 '14
First java submission. Needed to brush up on my java for school!
Edit: Oops, I don't deal with duplicates very well. Need to fix! Edit2: Fixed!
2
u/stonerbobo Aug 26 '14 edited Aug 26 '14
Here is a recursive, in-place version (partitioning in place), with randomized pivot selection in Python. I particularly like this way of partitioning - it is very clear IMO (most partition implementations confuse me):
any feedback is appreciated.
2
u/ArriMurri Aug 26 '14
This is my solution in clojure.
2
u/ctln_mrn Aug 26 '14
In Ruby:
1
u/frozensunshine 1 0 Aug 25 '14 edited Aug 25 '14
C. My first quicksort implementation. I'd love feedback on how to improve it (both time and space complexity). EDIT: Sorry, I just noticed the details of the question. I will edit the below code to make it do exactly what is asked, (I had implemented this a month ago and thereofre just pasted it) but right now, what this does is: generates a random sequence of 15 numbers and sorts it. No inputs taken. Outputs original sequence and sorted sequence.
1
u/supercheesepuffs Aug 26 '14
Here is my solution in C#:
1
u/sagan_radiation Aug 26 '14
Python 3.4. I check to see if the list contains only identical values as the termination condition. It would be more efficient to check if the list was already sorted but I don't know how to check that as a one-liner.
1
u/mpjan Aug 26 '14
Python:
1
u/Splanky222 0 0 Aug 27 '14 edited Aug 27 '14
C++ using the STL is about as pretty as it gets. Unless using std::partition is cheating :(
And a less dubious version using median-of-three to choose the pivot:
1
u/pan0ramic Aug 27 '14
I thought I would up the challenge a bit since to make my Java solution different than the others. Here is my Java in-place solution. You can send a list of <Number> although I should note that I do comparisons by .doubleValue(). Also, in my real solution I go through the trouble of doing my comparisons using a custom floating point math comparison suite (dealing with machine precision).
The solution was a bit trickier than I thought it would be!
1
u/kriskova Aug 27 '14
Ruby. Feel free to comment.
1
u/_neon_ Aug 27 '14
Here's a version in Ruby:
1
u/thinksInCode Aug 28 '14 edited Aug 28 '14
EDIT: I ended up with a new Groovy solution based on the Ruby solution by /u/threeifbywhiskey. Much nicer IMHO.
EDIT 2: Looks like this isn't quite right - it goes into infinite recursion if the input list has duplicate numbers. Still needs some work...
EDIT 3: Got it.
1
u/bjacks14 Aug 28 '14 edited Aug 28 '14
Um, well I'm new here, so hi all. I saw this reddit page and thought it was right up my alley. I don't have a professional education, however (only a few classes in high school with a very jolly CS teacher) and many of your examples were above my skill level. So I thought I would post my low-tech C++ solution. I am not sure how to properly format this comment, so I was unable to make the fancy grey block that the rest of you had. Sorry :( I couldn't find the code on the wiki page.
This first example is my first try. It's overly complicated. It takes in an array and returns an array. Why does it return an array? I'm not entirely sure... But it made sense when I did it.
C++ First Attempt
int* quicksort_original(int arr[], int arraySize) { int *a = arr;
End attempt one Is there a quicker way to format that code? I just put four spaces in front of every line. I think I did it right. Anways as you can see, that attempt was a little sloppy and has a tendency to break sometimes. But then while I was at work, I had a break through! I decided rather than working with seperate arrays, why not work on one array with different sort ranges. It's hard to explain (I'm not good with words) but here's my second (read better) attempt.
C++ Second Attempt
int quicksort(int arr[], int arraySize, int sortStart, int sortEnd) { //Pick a random number. int range = sortEnd - sortStart + 1; //these two statements create a random number between the given low and the given high (sortStart, sortEnd). int pivot = rand() % range + sortStart;
End second attempt That one ended up being cleaner and (as an added bonus) actually works every time. Which is nice. Um, but yeah, it's not as high tech as your chaps' responses, but I welcome criticism and opportunities to learn! I like that the second one works for any size array. The first one has a hard limit of 400. I hate how c++ arrays are static. I saw someone discuss using vectors instead of arrays, but my knowledge isn't that advance. Maybe some day I will learn.
Anyways, hope you all enjoyed my response. I apologize for formatting issues.
1
u/TiZ_EX1 Aug 29 '14
ECMAScript 6 on node.js. Decided to be straightforward about it. Takes a space-separated list of numbers on the command line.
1
u/[deleted] Aug 30 '14
C++:
Python:
1
u/mebob85 Sep 02 '14
Since it's an easy challenge, I'll share something that's a step above: a multithreaded quicksort.
This particular version relies on a Windows critical section, but that can easily be swapped out.
1
u/Busybyeski Sep 04 '14
Python: I tried to make this code very clean and readable.
This implementation uses the recommended recursion, recommended swap of two-element lists, and also gathers a 3-element sample to take the median of for a smartly chosen pivot.
1
u/[deleted] Aug 25 '14
C#. Contains custom Slice<T> because ArraySegment<T> didn't quite do what I wanted it to in this case; I think the solution is elegant, but having never tested my brand new collection made debugging this an exercise in faith.
Recursive quicksort with a borderline black magic partition function. Performs about seven times better than collection.OrderBy(item => item), but still about five times worse than a simple list.Sort().
Expected output for this program is simply "true", "true".
0
u/ralleMath Aug 25 '14
Haskell. I think not quite verbatim from Learn You a Haskell for Great Good!, but probably quite close since I read that section recently.
I did not bother with input, since I haven't gotten that far yet :p
0
u/[deleted] Aug 26 '14
[deleted] — view deleted comment