|
| 1 | +# Sorting Algorithms |
| 2 | +For the purpose of this module, we will be writing and discussing all sorting algorithms with the assumption that our goal is to sort items in ascending order. But be aware, this does not always have to be the case. |
| 3 | + |
| 4 | +## Day 1 - Why is it so important to sort data? |
| 5 | + |
| 6 | +### We're Always Searching |
| 7 | +With every passing day, users have less patience for slow apps. And rightfully so! And while a large part of why the applications we use now-a-days are so fast is due to the improvements in hardware over the last few decades, the software developer still has an important role to play in keeping everything moving quickly. |
| 8 | + |
| 9 | +As we write our applications, we should always be mindful of what operations are being done frequently, since optimizing these will have the biggest impact on the efficiency of our overall application. And regardless of *what* type of app you are creating, it is likely that one of the operations you will be relying on is ***searching***. We search [example 1], [example 2], and [example 3]. Because of this, it is essential that we optimize our searches. |
| 10 | + |
| 11 | +### Linear vs. Binary Search |
| 12 | +There are two common searching algorithms that developers are often introduced to when they are writing some of their first apps: linear search and binary search. Let's walk through the differences between them. |
| 13 | + |
| 14 | +#### Linear (Sequential) Search |
| 15 | + |
| 16 | +Sometimes referred to as sequential search, this algorithm is fairly straightforward. Given a set of data, traverse the dataset one item at a time until either you find the item you are looking for OR check every item in the set and verify the item you are looking for is not there. |
| 17 | + |
| 18 | +#### Binary Search |
| 19 | + |
| 20 | +The process of performing a binary search has a couple of extra steps. First, there is a *precondition* that the set of data you are searching is ***already sorted***. Then, the steps to search are: |
| 21 | + |
| 22 | +1. Compare the item in the middle of the data set to the item we are searching for. |
| 23 | + - If it is the same, stop. We found it and are done! |
| 24 | + - Else, if the item we are searching for is LESS than the item in the middle: |
| 25 | + - Eliminate the RHS of list. Repeat step 1 with only the LHS of list. |
| 26 | + - Else: ... |
| 27 | + |
| 28 | + |
| 29 | +A visualization comparing these two algorithms is shown below. |
| 30 | + |
| 31 | + |
| 32 | +#### Runtimes |
| 33 | + |
| 34 | +These two searching strategies have very different runtimes. |
| 35 | + |
| 36 | +**Linear Search:** O(n) |
| 37 | +**Binary Search:** O(log(n)) |
| 38 | + |
| 39 | +Looking at the above runtimes, it is clear that we want to avoid linear search. |
| 40 | +***However, we cannot perform binary search if our data isn't ALREADY SORTED!*** |
| 41 | + |
| 42 | +While the justification for *WHY* we want to sort our data is pretty clear, a harder question to answer is *HOW* do we want to sort our data. Over the next few days, we will explore several different sorting algorithms, examining the pros and cons of each. |
| 43 | + |
| 44 | +[(VIDEO) 15 Sorting Algorithms in 6 Minutes ](https://www.youtube.com/watch?v=kPRA0W1kECg) |
| 45 | + |
| 46 | +## Iterative Sorting Algorithms |
| 47 | + |
| 48 | +### Selection Sort |
| 49 | +***Selection Sort*** is an algorithm that many of you have actually used before. Imagine that you have several playing cards you need to put in order. You start off by looking for the lowest card, and when you find it, put it at the front of your hand. Then, you look for the second lowest card and insert it directly behind the first card. You repeat this process, selecting the next lowest card and moving it behind the most recently placed card, until you have moved all cards into the right place. This is ***Selection Sort***. |
| 50 | + |
| 51 | +An example of this algorithm being applied to an array with 10 numerical elements can be seen in the video below. |
| 52 | + |
| 53 | +[(VIDEO) Select-sort with Gypsy folk dance ](https://www.youtube.com/watch?v=Ns4TPTC8whw) |
| 54 | + |
| 55 | +>CHALLENGE: Before scrolling down, try outlining the steps for this algorithm from what you observed in the video above! |
| 56 | +
|
| 57 | + |
| 58 | +#### Algorithm |
| 59 | +1. Start with current index = 0 |
| 60 | + |
| 61 | +2. For all indices EXCEPT last: |
| 62 | + |
| 63 | + a. Loop through elements on right-hand-side |
| 64 | + of current index and find smallest element |
| 65 | + |
| 66 | + b. Swap element at current index with |
| 67 | + smallest element found in above loop |
| 68 | + |
| 69 | +#### Implementation in Python |
| 70 | +``` |
| 71 | +def selectionSort(): |
| 72 | + // For all indices EXCEPT last: |
| 73 | + for i in range(0, arr.length-2): |
| 74 | + var cur_min_index = i; |
| 75 | + // 1. Loop through elements on right-hand-side |
| 76 | + // of current index and find smallest element |
| 77 | + for j in range(i+1, arr.length-2): |
| 78 | + if arr[j] < arr[cur_min_index]: |
| 79 | + cur_min_index = j; |
| 80 | + // 2. Swap element at current index with |
| 81 | + // smallest element found in above loop |
| 82 | + int temp = arr[i]; |
| 83 | + arr[i] = arr[cur_min_index]; |
| 84 | + arr[cur_min_index] = temp; |
| 85 | + // return sorted array |
| 86 | + return arr; |
| 87 | +
|
| 88 | +// try it out |
| 89 | +var arr = [2,5,9,7,4,1,3,8,6]; |
| 90 | +print( "Unsorted array: " + arr); |
| 91 | +arr = selectionSort( arr ); |
| 92 | +print( "Sorted array: " + arr); |
| 93 | +
|
| 94 | +``` |
| 95 | + |
| 96 | +#### Real-World Applications |
| 97 | +While ***Selection Sort*** is one of the easier sorting algorithms to understand and implement, it has one major drawback - its efficiency. |
| 98 | + |
| 99 | +Recall that the runtime complexity of an algorithm, often expressed using *Big O notation*, tells us how the amount of operations our algorithm requires will grow as the size of our input grows. ***Selection Sort*** will have a runtime of O(n²) in *all* cases, making it impractical to use with many large, real-world data sets. |
| 100 | + |
| 101 | +#### Check for understanding |
| 102 | +1. Is ***Selection Sort*** a comparison sorting algorithm? |
| 103 | + <details><summary>Answer</summary> Yes, since to <i>select</i> the desired element, we compare a current value to the rest of the "unsorted" segment of our list or array. |
| 104 | + </details> |
| 105 | + |
| 106 | +2. Why do we end our loop before processing the item in the last index of an array when performing ***Selection Sort***? |
| 107 | + <details><summary>Answer</summary> By the nature of how this algorithm works, if all other elements have been sorted, the last element will have been moved to the correct index. |
| 108 | + |
| 109 | +3. When using ***Selection Sort***, what is the difference between the order or arrangement of elements in *best case* versus *worst case*? |
| 110 | + <details><summary>Answer</summary> None, since the same number of operations will be performed <b>regardless</b> of how elements are ordered. |
| 111 | + </details> |
| 112 | + |
| 113 | +4. When using ***Selection Sort***, what would be the runtime of sorting elements in the best, average, and worst cases? |
| 114 | + <details><summary>Answer</summary> <ul> |
| 115 | + <li>Best case: O(n²)</li> |
| 116 | + <li>Average case: O(n²)</li> |
| 117 | + <li>Worst case: O(n²)</li> |
| 118 | + </ul> |
| 119 | + </details> |
| 120 | +5. Show how the array **[4, 8, 3, 1, 9, 6]** changes as it is being sorted using ***Selection Sort***. To do this, write out the contents of the array after each pass of the algorithm. (_hint...we should only need n-1 passes to sort the array, where n is the size_) |
| 121 | + <details><summary>Answer</summary> <pre><samp>[1, 8, 3, 4, 9, 6] |
| 122 | + [1, 3, 8, 4, 9, 6] |
| 123 | + [1, 3, 4, 8, 9, 6] |
| 124 | + [1, 3, 4, 6, 9, 8] |
| 125 | + [1, 3, 4, 6, 8, 9] </samp></pre></details> |
| 126 | + |
| 127 | +### Insertion Sort |
| 128 | +[overview] |
| 129 | + |
| 130 | +[(VIDEO) Insert-sort with Romanian folk dance ](https://www.youtube.com/watch?v=ROalU379l3U) |
| 131 | + |
| 132 | +#### Algorithm |
| 133 | +1. Separate the first element from the rest of the array. Consider it a sorted list of one element. |
| 134 | + |
| 135 | +2. For all other indices, beginning with [1]: |
| 136 | + |
| 137 | + a. Copy the current item into a temp variable |
| 138 | + |
| 139 | + b. Iterate to the left until you find the correct index in the "sorted" part of the array at which this element should be inserted |
| 140 | + - Shift items over to the right as you iterate |
| 141 | + |
| 142 | + c. When the right index is found, copy temp into this position |
| 143 | + |
| 144 | +#### Implementation in Python |
| 145 | +``` |
| 146 | +def insertionSort(): |
| 147 | + // TO-DO |
| 148 | +
|
| 149 | +
|
| 150 | +// try it out |
| 151 | +var arr = [2,5,9,7,4,1,3,8,6]; |
| 152 | +print( "Unsorted array: " + arr); |
| 153 | +arr = insertionSort( arr ); |
| 154 | +print( "Sorted array: " + arr); |
| 155 | +
|
| 156 | +``` |
| 157 | + |
| 158 | +#### Real-World Applications |
| 159 | +While ***Insertion Sort*** is... |
| 160 | + |
| 161 | +#### Check for understanding |
| 162 | +1. Is ***Insertion Sort*** a comparison sorting algorithm? |
| 163 | + <details><summary>Answer</summary>Yes, since to find the correct index at which we "insert" the current element we are sorting, we compare it to the rest of the "sorted" segment of our list or array. |
| 164 | + </details> |
| 165 | + |
| 166 | +2. Consider a scenario in which you have _____. Which sorting algorithm would you chose and WHY? |
| 167 | + |
| 168 | +3. When using ***Insertion Sort***, what is the difference between the order or arrangement of elements in *best case* versus *worst case*? |
| 169 | + <details><summary>Answer</summary>When performing <i><b>Insertion Sort</b></i>, the algorithm runs more efficiently if the elements are already mostly sorted. When the original array is close to sorted order, fewer comparisons are required to sort it. But if the array is in reverse-sorted order, the number of comparisons that need to be done increases significantly. |
| 170 | + |
| 171 | + For example: `[5, 4, 3, 2, 1]` |
| 172 | + |
| 173 | + When inserting the 1 into the correct part of the array, we have to compare it with *every* other number. While this is not such a big deal in an array with 5 elements, it gets ***very*** costly as that array becomes bigger. |
| 174 | + </details> |
| 175 | + |
| 176 | +4. When using ***Insertion Sort***, what would be the runtime of sorting elements in the best, average, and worst cases? |
| 177 | + <details><summary>Answer</summary> |
| 178 | + <ul><li>Best case: O( )</li> |
| 179 | + <li>Average case: O( )</li> |
| 180 | + <li>Worst case: O( )</li> |
| 181 | + </details> |
| 182 | + |
| 183 | +5. Show how the array **[4, 8, 3, 1, 9, 6]** changes as it is being sorted using ***Insertion Sort***. To do this, write out the contents of the array after each pass of the algorithm. (_hint...we should only need n-1 passes to sort the array, where n is the size_) |
| 184 | + <details><summary>Answer</summary> <pre><samp>[4, 8, 3, 1, 9, 6] (comparison done, no swap made) |
| 185 | + [3, 4, 8, 1, 9, 6] |
| 186 | + [1, 3, 4, 8, 9, 6] |
| 187 | + [1, 3, 4, 8, 9, 6] (comparison done, no swap made) |
| 188 | + [1, 3, 4, 6, 8, 9]</samp></pre></details> |
| 189 | + |
| 190 | +### Stretch Goals |
| 191 | + |
| 192 | +#### There are a few "order n" sorting algorithms whose runtime will be linear, even in a worst case scenario. |
| 193 | +Look into Radix Sort and Count Sort. |
| 194 | +- How are these algorithms different from other iterative sorting algorithms? |
| 195 | + - What are the advantages/disadvantages to this type of sorting algorithm? |
| 196 | +- Take a look a the psuedocode for these algorithms and try implementing one or both of them in Python. |
| 197 | + |
| 198 | +#### Some other iterative sorting algorithms include Bubble Sort and Bogo Sort. |
| 199 | +- Summarize how they work in 2-3 sentences. |
| 200 | +- Which algorithm has a better runtime? Explain why. |
| 201 | + |
| 202 | + |
| 203 | +## Day 2 - A Better Way to Sort |
| 204 | + |
| 205 | +### Divide & Conquer |
| 206 | +>A divide-and-conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved directly. |
| 207 | +-Wikipedia |
| 208 | + |
| 209 | +This approach can be very useful when sorting. By breaking up our original data set into subsets and recursively sorting each subset, we can obtain significant performance gains. |
| 210 | + |
| 211 | +### Recursion Recap |
| 212 | +Remember that when writing a recursive algorithm, there are two pieces we have to define: |
| 213 | +- Base case |
| 214 | +- Recursive case |
| 215 | + |
| 216 | +Recursive cases *must* be written in a way that will eventually allow us to reach the base case. Otherwise, infinite recursion will lead to ***STACK OVERFLOW***! |
| 217 | + |
| 218 | +## Recursive Sorting Algorithms |
| 219 | + |
| 220 | +### Merge Sort |
| 221 | +[overview] |
| 222 | + |
| 223 | +[(VIDEO) Merge-sort with Transylvanian-saxon (German) folk dance ](https://www.youtube.com/watch?v=XaqR3G_NVoo) |
| 224 | + |
| 225 | +#### Algorithm |
| 226 | +``` |
| 227 | +TBC |
| 228 | +``` |
| 229 | +>CHALLENGE: One implementation is shown below, but take a stab at writing the code for this yourself before scrolling down! |
| 230 | +
|
| 231 | +#### Implementation in Python |
| 232 | +``` |
| 233 | +def mergeSort(): |
| 234 | + //TBC |
| 235 | +
|
| 236 | +// try it out |
| 237 | +var arr = [2,5,9,7,4,1,3,8,6]; |
| 238 | +print( "Unsorted array: " + arr); |
| 239 | +arr = mergeSort( arr ); |
| 240 | +print( "Sorted array: " + arr); |
| 241 | +
|
| 242 | +``` |
| 243 | + |
| 244 | +#### Real-World Applications |
| 245 | +Have you ever wondered how some of the languages you use actually implement their built-in `sort()` functions? Many of them actually utilize the ***Merge Sort*** algorithm! |
| 246 | + |
| 247 | +#### Check for understanding |
| 248 | +1. TBD |
| 249 | + <details><summary>Answer</summary> ... </details> |
| 250 | + |
| 251 | +2. When using ***Merge Sort***, what is the difference between the order or arrangement of elements in *best case* versus *worst case*? |
| 252 | + <details><summary>Answer</summary> ... </details> |
| 253 | + |
| 254 | +3. When using ***Merge Sort***, what would be the runtime of sorting elements in the best, average, and worst cases? |
| 255 | + <details><summary>Answer</summary> |
| 256 | + <ul><li>Best case: O(nlog(n))</li> |
| 257 | + <li>Average case: O(nlog(n))</li> |
| 258 | + <li>Worst case: O(nlog(n))</li> |
| 259 | + </details> |
| 260 | + |
| 261 | +4. Show how the array **[4, 8, 3, 1, 9, 6]** changes as it is being sorted using ***Merge Sort***. To do this, write out the contents of the array after each pass of the algorithm. (_hint...we should only need n-1 passes to sort the array, where n is the size_) |
| 262 | + <details><summary>Answer</summary> <pre><samp> [4, 8, 3, 1, 9, 6] // divide |
| 263 | + / \ |
| 264 | + [4, 8, 3] [1, 9, 6] |
| 265 | + / \ / \ |
| 266 | + [4, 8] [3] [1, 9] [6] |
| 267 | + / \ | / \ | |
| 268 | + [4] [8] [3] [1] [9] [6] // merge |
| 269 | + \ / | \ / | |
| 270 | + [4, 8] [3] [1, 9] [6] |
| 271 | + \ / \ / |
| 272 | + [3, 4, 8] [1, 6, 9] |
| 273 | + \ / |
| 274 | + [1, 3, 4, 6, 8, 9] </samp></pre></details> |
| 275 | + |
| 276 | +### Quick Sort |
| 277 | +[overview] |
| 278 | + |
| 279 | +[(VIDEO) Quick-sort with Hungarian folk dance ](https://www.youtube.com/watch?v=ywWBy6J5gz8) |
| 280 | + |
| 281 | + |
| 282 | +#### Algorithm |
| 283 | +``` |
| 284 | +TBC |
| 285 | +``` |
| 286 | + |
| 287 | +#### Implementation in Python |
| 288 | +``` |
| 289 | +def quickSort(): |
| 290 | + // TBC |
| 291 | +
|
| 292 | +
|
| 293 | +// try it out |
| 294 | +var arr = [2,5,9,7,4,1,3,8,6]; |
| 295 | +print( "Unsorted array: " + arr); |
| 296 | +arr = quickSort( arr ); |
| 297 | +print( "Sorted array: " + arr); |
| 298 | +
|
| 299 | +``` |
| 300 | + |
| 301 | +#### Real-World Applications |
| 302 | +While ***Quick Sort*** has "quick" in its name, it is typically not used as frequently as Merge Sort. Although it *is* quick in a best case scenario, worst case for ***Quick Sort*** is *very* bad. Because of this, it is not often chosen for production. |
| 303 | + |
| 304 | +#### Check for understanding |
| 305 | +1. In ***Quick Sort***, if the leftmost element of an already sorted array is chosen as the pivot, this leads to worst case performance. Explain why. |
| 306 | + |
| 307 | +2. Consider a scenario in which you have _____. Which recursive sorting algorithm would you chose and WHY? |
| 308 | + |
| 309 | + |
| 310 | +3. When using ***Quick Sort***, what would be the runtime of sorting elements in the best, average, and worst cases? |
| 311 | + <details><summary>Answer</summary> |
| 312 | + <ul><li>Best case: O(nlog(n))</li> |
| 313 | + <li>Average case: O(nlog(n))</li> |
| 314 | + <li>Worst case: O(n²)</li> |
| 315 | + </details> |
| 316 | + |
| 317 | +4. Show how the array **[4, 8, 3, 1, 9, 6]** changes as it is being sorted using ***Quick Sort***. To do this, write out the contents of the array after each pass of the algorithm. (_assume the pivot will be the middle index, mid=len of subarray / 2_) |
| 318 | + <details><summary>Answer</summary> <pre><samp>[1, 8, 3, 4, 9, 6] // pivot = 1 |
| 319 | + // Quick Sort LHS, RHS of 1 |
| 320 | + [1, 8, 3, 4, 9, 6] // LHS done ✓ |
| 321 | + ✓ |
| 322 | + [1, 8, 3, 4, 9, 6] // RHS pivot = 4 |
| 323 | + ✓ |
| 324 | + [1, 3, 4, 8, 9, 6] |
| 325 | + ✓ |
| 326 | + // Quick Sort LHS, RHS of 4 |
| 327 | + [1, 3, 4, 8, 9, 6] // LHS done ✓ |
| 328 | + ✓ ✓ ✓ |
| 329 | + [1, 3, 4, 8, 9, 6] // RHS pivot = 9 |
| 330 | + ✓ ✓ ✓ |
| 331 | + [1, 3, 4, 8, 6, 9] |
| 332 | + ✓ ✓ ✓ |
| 333 | + // Quick Sort LHS, RHS of 9 |
| 334 | + [1, 3, 4, 8, 6, 9] // RHS done ✓ |
| 335 | + ✓ ✓ ✓ ✓ |
| 336 | + [1, 3, 4, 8, 6, 9] // LHS pivot = 6 |
| 337 | + ✓ ✓ ✓ ✓ |
| 338 | + [1, 3, 4, 6, 8, 9] |
| 339 | + ✓ ✓ ✓ ✓ |
| 340 | + // Quick Sort LHS, RHS of 6 |
| 341 | + [1, 3, 4, 6, 8, 9] // LHS, RHS done ✓ |
| 342 | + ✓ ✓ ✓ ✓ ✓ ✓</samp></pre></details> |
| 343 | + |
| 344 | +### Stretch Goals |
| 345 | + |
| 346 | +#### Tim Sort is a combination of the Merge Sort and Insertion Sort algorithms. |
| 347 | +- What programming languages use **Tim Sort** to implement their built-in `sort()` functions? |
| 348 | +- If an interviewer asked you to describe the **Tim Sort** algorithm in 3-4 sentences, what would you say? |
| 349 | +- Can you implement **Tim Sort** in Python? |
0 commit comments