Performance of Sorting Algorithms
We introduced four sorting algorithms in this chapter: selection sort, bubble sort, merge sort, and quicksort. In addition, we performed a basic analysis of the time complexity of each algorithm. In this section, we’ll revisit that topic and compare sorting algorithms based on their performance, helping us understand what algorithm to choose based on the situation.
Overall Comparison
The list below shows the overall result of our time complexity analysis for each algorithm.
- Selection Sort:
- Bubble Sort:
- Merge Sort:
- Quicksort Average Case:
- Quicksort Worst Case:
We have expressed the amount of time each algorithm takes to complete in terms of the size of the original input
One of the easiest ways to compare two functions is to graph them, just like we’ve learned to do in our math classes. The diagram below shows a graph containing the functions
First, notice that the scale along the X axis (representing values of
As we can see, the value of
Based on that assessment alone, we might conclude that we should always use merge sort! It is guaranteed to run in
Choosing Sorting Algorithms
The choice of which sorting algorithm to use in our programs largely comes down to what we know about the data we have, and how that information can impact the performance of the algorithm. This is true for many other algorithms we will write in this class. Many times there are multiple methods to perform a task, such as sorting, and the choice of which method we use largely depends on what we expect our input data to be.
For example, consider the case where our input data is nearly sorted. In that instance, most of the items are in the correct order, but a few of them, maybe less than
Likewise, if we know that our data is random and uniformly distributed, we might want to choose quicksort. Even though quicksort has very slow performance in the worst case, if our data is properly random and distributed, research shows that it will have better real-world performance than most other sorting algorithms in that instance.
Finally, what if we know nothing about our input data? In that case, we might want to choose merge sort as the safe bet. It is guaranteed to be no worse than