In this lesson we introduce a new topic: sorting. Sorting algorithms are both fun to implement, and fun to analyze. We’ll get to practice with iterative and recursive algorithms, and with algorithm analysis. Let’s get started!
Sorting is the process of putting things in order. While it may not feel at first like the most interesting problem to solve, sorting is a core building block for many other algorithms. Competitions continue to be held for systems that can sort large numbers of items. And, despite being a very old problem, new sorting algorithms continue to be released with new performance characteristics. (The sorting algorithm used by default by Java, Python, and other languages dates only to 2002.)
For the sake of simplicity most of our examples will follow a few conventions:
intarrays. We can sort anything that’s
Comparablein Kotlin, but using integers makes the comparisons a bit simpler
As we examine the performance of our sorting algorithms we’ll look at a few things:
And, while there are many sorting algorithms, we’ll focus on just a few due to their interesting performance characteristics or real world use cases. Specifically, we’ll implement or analyze:
And maybe a few more along the way!
As a warm up, let’s implement and analyze a simple method to determine whether an integer array is already sorted. We can use this as needed to check our work as we develop additional sorting algorithms!
Now let’s actually implement a sorting algorithm.
Our first algorithm, Bubble Sort, follows naturally from the
isSorted method that we implement above.
But, rather than just returning when we find out-of-order elements, we’ll fix them!
If we do this enough times, the array should end up sorted.
Next, let’s analyze the performance of our bubble sort implementation. We’ll look at both best and worst case inputs, and try to say something general about the performance of the algorithm.
Next, let’s look at a different approach called insertion sort. You’ll implement this on the next homework problem. But let’s walk through the approach visually to get you off to a good start!
Create a method
sort that accepts non-null
IntArray and sorts them in ascending order.
You should sort the array in place, meaning that you modify the original array,
and return the number of swaps required to sort the array as an
That's how we'll know that you've correctly implemented insertion sort.
To receive credit implement insertion sort as follows. Have the sorted part start at the left and grow to the right. Each step takes the left-most value from the unsorted part of the array and move it leftward, swapping elements until it is in the correct place. Do not swap equal values. This will make your sort unstable and cause you to fail the test suites.
Need more practice? Head over to the practice page.