1. Home
  2. Explore
  3. Computer Science
  4. Comparison-Based Sorting

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Comparison-Based Sorting

Transcript

Sorting algorithms are a pretty big deal when it comes to computing and being able to do things efficiently and effectively. So we'll review some basic sorting algorithms and we'll look at some features of those sorting algorithms that give us an upper bound on their performance. In particular, we'll look at comparison based sorting right now and see if we're comparing values within our set of data, what's the best we can do for sorting them? So, if we have some input,

such as an array of n items that need to be sorted and We have a consistent way to compare all those items, meaning there's an ordering for them, "greater than" and "less than" operators, then we want to output an array with all n items sorted from least to greatest. We could just as easily do from greatest to least, but we'll focus on this one direction. There are some more strict features we could aim for, such as stable sorting. This is the kind of thing where if you had a spreadsheet and you sorted it first by first name and then by last name, if two people shared the same last name, they would still be in order by first name. So, doing that last name sort doesn't jumble your first name results for tie-breaking. Stable sorting typically deals mostly with tie-breaking.

So, that's a feature that we may sometimes want. If items have an equal value, then they maintain their original order of whatever previous order they were in, whether it was based on a sort, or based on the order that the user had entered them in or anything like that. Sometimes we want to keep that information and not lose it. So, we will do a very speedy review of some of the very simplest sorting algorithms, and then we will do a little more in-depth review of a few of the more complex and more efficient sorting algorithms, and then we will look at a lower bound on complexity, meaning the fastest that you can get for a comparison-based sort.

One of the simplest algorithms is Insertion sort where we take each item in the array "A" and we compare it with every item before it until we found the place for it. We essentially find the right place to insert that in the result list, so we move larger items slightly to the right until they cannot move anymore because we would be passing data that they should not pass. So, it is stable and it can be done "in-place" meaning we don't need any extra memory because we're just shifting things until they're inserted in that right location there.

However, it's O(N^2) which is not a fun performance category to live in especially for sorting. Selection sort is also pretty simple. For every item in the array, we find the minimum of each unsorted item after and including "X", meaning we find the first minimum, the second minimum, the third minimum, and so on. So, we then just swap with that minimum and consider that particular position sorted. We no longer have to look at that location. So, once I find the first minimum, I can ignore index 0. Once I find the second minimum, I can ignore index 1, and once I find the third minimum, I can ignore index 2.

It can be done in-place and it can be made stable. So you can keep the ordering as long as you shift in a smart way, you can keep tie-breaking on those previous orderings. But it's still O(N^2) and it's a pretty slow O(N^2) as these things go. Bubble sort is another option where we flip through the array looking at each unsorted pair of items and swapping them if they're out of order and

we can quit once we've made it through the array with no more swaps needing to be done. This is a neat algorithm in that the largest items sort of "bubble up" to the top to the furthest out indexes on each iteration that we do, so it's sort of does like selection sort where here though, The max will be located at the right location after one iteration through. It does a little nicer than selection sort in some sense because other items will get swapped closer to their correct place as you iterate through. And you can stop at the last swapped item from the prior step as well so you don't have to keep re-looking at items that you had already swapped into the correct places.

It's stable, and it can be done in-place. So, low memory footprint. It's still O(N^2). Its best performance is if the array is nearly sorted already. Merge sort is likely one of the first "divide-and-conquer" algorithms that you have seen if you've seen merge sort already before, along with binary search typically. So you divide-and-conquer on your array where you take this assumption that a one-item array is already sorted, because it can't be out of order with anyone else, and then from that, you build up this idea that if there were two items, you could look and see whether they're out of order and swap them and if there were more than you can simply split down

until you have only pairs or singletons. And then the big trick is when you recursively call merge sort on each copy of half of the array and then you have to, as you come up, from the recursion merge those portions of the array together into a single sorted array and return that array. So it is stable. It is written fastest if it's written not to be in-place. You can do merge sort in-place, but it gets more complicated and you have to do more checks of things. It's easiest if you copy off those portions of the array and then you merge them back in into a full-sized array.

But it's O(NlogN), which is a better category of behavior to be in than the N^2's we've been seeing so far. It is also very easy to parallelize it, meaning run it in different threads or different processes to handle different portions of the array. So here's a visual for merge sort. If we have this full array here, we would recursively call merge sort on the first three items and recursively call it on the second three items, the last three items, and then from that we would split again for each of those, since there are three in those two different sides, then we split into a pair and a singleton. The singleton is easy because it's already sorted. The pair might require a swap,

which can, by the way, be treated as just splitting those down to singletons and then merging them together into an array of size two. So, if you were to merge them, you look between the two arrays and choose the minimum from either of those two arrays, which will always be the first item in that array. And then you put them in the correct order in the merged here we have 27 and the 16 and 38 that need to be merged, and so we can choose the lowest item which is 16, the next lowest item is 27, and the next only remaining item is 38. And you see that down the other sort of branch of this split in merge sort too. It merges back together to get its sorted array of 3 and then from those 2 arrays of 3, we simply look at the

lowest value in either. So that's one comparison, 12 and 16. We choose the 12, then we're comparing 27 and 16. We would choose the 16, then between the 27s, we can choose, they're tied. It's not a big deal, and then we end up with the 38 and the 39 being our choices left. So, it has log N recursive calls and log N merge steps and at each level, the merge itself is an O(N) operation because I'm not comparing every item to every other item. I'm only comparing 12 to 16 and then once I've chosen 12, I remove it, and I'm only comparing 16 to 27, and so on.

Heapsort is another option that's using this idea of a heap and that a heap gives us these nice LogN operations for finding minimum or maximum and essentially, we can build the array backwards. If we have a max-heap, then we can get max from that heap, put it at the end of the heap, and then ignore that when doing our heap operations from then on, and we just keep repeating that until the heap is empty. So we'll be dealing with a smaller and smaller portion of the array being treated as the heap

and once we pull the max off, we put it into that last location that now is no longer considered part of the heap. It's not stable because heaps don't guarantee us as nice of features around ordering, so we may lose our original ordering between tied items, but it can be done in place because the heap is just an array and we're just pulling the max off and putting that at the end of the heap, so it's somewhat similar to selection sort that shows the minimum,

but we're choosing the max and we can get that max faster because we are building a heap and using the heap operations on it to get that logN performance from choosing the max. So we choose the max N times, to choose the max is a log N operation if we're maintaining the heap property after choosing the max, and therefore it's N times logN performance in the worst case.

Quicksort is the last comparison-based sorting algorithm we'll look at, and It relies on this idea of choosing a "pivot" that you will put all data to the left or to the right of that particular pivot value, and so this allows us to do a divide-and-conquer where we choose a pivot that we hope will split our data in half; if we're very lucky, we choose the very middle value and all values lower than that pivot go to the left and then we recur on that portion of the array and all values higher than that pivot go to the right and we recur on that portion of the array.

We also get a beautiful feature that the pivot will be in its exact final location once we have moved all items left or right of it. So we choose some pivot value. Usually we have to choose it at random because we don't know which value is going to be good or bad for being our pivot until we've used it and then we partition the array according to the pivot, where we walk through both ends of A to find items that are out of place meaning they're above the pivot but should be below it or below the pivot but should be above it and we swap them.

When we reach the middle, then we swap the pivot into that location and now the pivot is in the right place for its final location. Whether it's been a good pivot or not, at the very least we get the benefit that the pivot itself is correctly located now and we can ignore it for all of our recursive calls. So we recursively call with the left partition of values that were lower than the pivot and we recursively call with the right partition of values that were higher than the pivot.

Again, it is not stable because it won't preserve the ordering necessarily of those items that were moved from one side of a pivot to another, but it is in-place. It can be done in-place. you'll still call recursively, but you'll call with ranges of Indexes for that array and you'll only modify items within those ranges. There's no merge step that has to bring us back up either. So

It's O(N^2) in the worst case, and that worst case is if it was already sorted and we choose the worst possible pivot at every location. So say we chose the lowest value then the next lowest value and the next lowest and next lowest well, as a pivot the lowest value the minimum value is terrible because it has nothing to the left and everything but itself to the right, and so on and so on. So if we chose very unluckily or in particular because the array was already sorted we are messing up that sort and then having to redo it, Then we end up with very bad behavior of O(N^2).

Its average behavior is O(NlogN) and in practical performance if we are randomly selecting our pivots, it's usually a faster NlogN than the other NlogN algorithms, which is a bit confusing because it's worst case category is worse than them. So to give some perspective on how important these kinds of algorithm choices are,

if we look at insertion sort, which we knew was N^2, then if we perform insertion sort on a few thousand items, it's functionally instant. It's very quick for, you know, human perception. If we perform it on a million items it can take a second on a supercomputer but hours on our typical user's computer, and if we perform it on a billion items, it can take weeks on a supercomputer and years on the average home computer. If we perform merge sort, which is N log N, then we're instant up to the millions of items, basically. We're in the minutes category for billions of items on a home computer and if we use quicksort, which was

confusingly only average of N log N because it's got some of those features that give us the pivot located in the right space and the good behavior on average, it actually is in the category of minutes even for billions of items. So, these are good. It's important that we choose the right algorithm for the job and we can see that yet again in these cases.

However, it would be really helpful to take a category of algorithms like these comparison-based algorithms and figure out what is the best that they can possibly do? Is it worth pursuing a better comparison-based algorithm, or should we say we've pretty much solved this category? And maybe there's another category that can do better than that. So can we do better than this N log N that we've seen so far?

Because all that really is is an upper bound on the worst case behavior and as we saw with quicksort, the upper bound is not always the most informative information about an algorithm. It's very important to know what the worst situation we might face could be, but it's not the only or even necessarily the most informative information all of the time. So we would like to find a lower bound on worst case behaviors for sorting algorithms that use comparison; the minimum amount of time it would take any comparison-based sort algorithm. and we can do this by basing our proof on the idea of a decision tree where we're making decisions that are those comparisons.

So, every node in our decision tree is a set of possible orderings Where A might be less than B, and B might be less than C, and that is one of the possible orderings. When we've done no comparisons, any ordering is possible for the correct final ordering. So these are the way that lists should be ordered if we knew which comparisons were true and which comparisons were false. So all possible orders exist in the top node, and then we consider, What if we found one comparison to be true or false? So if we found that A was less than B,

that leaves us only a few of the possible future worlds there where it could be less than B, and B could be less than C, or A could be less than C, and C could be less than B, and so on. So if we do comparisons, then we narrow down this world of possibilities in the decision tree. That single comparison eliminates half of the possible orderings from the parent, so we can already see a little bit of a hint that there may be a logarithm built in here because we've got this behavior of eliminating half.

The comparison links a child with C or, links the parent to a child with the only possible remaining orderings there. So, any possible run of a comparison-based sorting algorithm will correspond to a root-to-leaf path in that tree, so depending on which things ought to go where, we will always at least have to compare once to find out something to be true or false if we are using a comparison-based sorting algorithm.

So, an example of this if we took that full three-value possibility world there with A, B and C then we make those different comparisons and we find ourselves in one of these various worlds here and you can see that the tree has a minimum depth of two before we reach a leaf, meaning we had to do at least two comparisons there, and a maximum length of 3 comparisons to reach a leaf node in these lower-down ones. There will be N factorial (N!)

permutations in that tree of possible ways that the values that we're sorting could need to be arranged. That means that there will be N factorial leaves. So, the height of the tree will be log of N factorial. because we're splitting in half every time through there.

So, let's break the log of N factorial down a little bit, I won't belabor the point on the math here but, we know that log of N factorial is log of N times N minus 1 times N minus 2 all the way down to 1. So we just expanded the factorial there. You may or may not remember that algebraically, you are allowed to break out multiplications inside of a logarithm to be additions between logarithms as long as it has the same base. Then, we can turn log N times N minus 1 Into log N plus log N minus 1, so these are equivalent. and they give us the result for just splitting out those different multiplications inside of the logarithm.

Mathematically, using some sequence rules, if we we know that this sequence here all the way down to log 2 and log 1 is greater than or equal to the sequence going from log of N to log of N over 2. So if we're looking for this lower bound then we're okay just saying "we know that this original thing is greater than or equal to our next step here", and that sequence is greater than or equal to N over 2 times log of N over 2

so we can already see that N over 2 could be thrown out and i'm sorry, not thrown out, but the over 2 could be thrown out and we're starting to see a behavior that looks like an N log N and in fact, we can reason that that is greater than or equal to N over ( 2 log N ) minus N over 2, which is big-Omega of N log N. So what we've proven is that comparison-based sorting algorithms have to run in at least N log N time. They're the best comparison-based sorting algorithm we could possibly devise will require at least N log N time as its Big-O.

But, we could sort without using comparisons and we'll look at some sorting algorithms soon that allow us to do that. So for now, comparison-based sorting looks like this, where we can sometimes get stable sorts, and we may be able to do it without additional memory and do it in-place. The best algorithms don't have those two features combined, but they do provide us with N log N behavior.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent