r/compsci • • Aug 14 '13

Algorithims Everyone Should Know?

What are some of you're favourite algoritms or concepts that you think everyone should know, whether they solve problems that crop up frequently, or are just beautiful in their construction?

379 Upvotes

118 comments sorted by

View all comments

Show parent comment

10

u/blexim Aug 14 '13

Quicksort's worst case complexity is affected in a big why by your pivot selection strategy. You can make it O(n log n) by using the median element as your pivot (which takes O(n) time to find). In practice you wouldn't want to do this because you end up slower for pretty much any practical case. Mergesort is indeed easier to analyse, but it's not used in practice as much as quicksort. This isn't because it has a fancy name, it's because it's an in place sort (so uses less memory) and is empirically faster for most applications.

3

u/Porges Aug 14 '13

because it's an in place sort (so uses less memory)

Mergesort can be done in-place (Knuth, as usual, has an exercise for this).

Mergesort is also important because it can be easily parallelized. You can also do a hybrid Mergesort and use QuickSort on each processor for sorting its portion and then Mergesort to put them all back together.

Timsort (the default sort in Python & the JDK, along with Android) is a hybrid Merge/Insertion sort, so Mergesort may in fact be used more than Quicksort considering the number of Android devices...

4

u/oligocordicul Aug 15 '13

Don't think anyone mentioned, but mergesort is also a stable sort, quicksort isn't. And there are times when this is important.