You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 0aabdfe
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: readme.md
+71-99Lines changed: 71 additions & 99 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,15 +1,15 @@
1
1
# Sorting Algorithms
2
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
3
4
-
## Day 1 - Why Is It So Important to Sort Data?
4
+
## Part 1: Why is it So Important to Sort Data?
5
5
6
6
### We're Always Searching
7
7
Users do not have patience for slow apps. And rightfully so! While a a big reason why the applications we use now-a-days are so fast is due to the improvements made in hardware over the last few decades, the software developer still has an important role to play in keeping everything moving quickly.
8
8
9
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 for songs to add to a playlist, videos to watch, people we need to talk to and so much more. Because of this, it is essential that we optimize our searches.
10
10
11
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.
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
13
14
14
#### Linear (Sequential) Search
15
15
@@ -47,7 +47,33 @@ While the justification for *WHY* we want to sort our data is pretty clear, a ha
47
47
48
48
[Just for fun...(VIDEO) 15 Sorting Algorithms in 6 Minutes ](https://www.youtube.com/watch?v=kPRA0W1kECg)
49
49
50
-
## Iterative Sorting Algorithms
50
+
## Part 2: Iterative Sorting Algorithms
51
+
52
+
### Insertion Sort
53
+
Think back to class or team picture day. Everyone stands in a line facing the photographer. Starting at the left-hand side of the line, the photographer checks to make sure each person is taller than the person next to them. If they are shorter, the photographer pulls them out and shifts people over to the right until he or she finds the right spot for this person. They then insert them back into the line. This process repeats until the photographer reaches the last person on the right-hand side, who must be the tallest person in the group. This is ***Insertion Sort***.
54
+
55
+
[(VIDEO) Insert-sort with Romanian folk dance](https://www.youtube.com/watch?v=ROalU379l3U)
56
+
57
+
[](https://www.youtube.com/watch?v=ROalU379l3U)
58
+
59
+
#### Algorithm
60
+
1. Separate the first element from the rest of the array. Think about it as a sorted list of one element.
61
+
62
+
2. For all other indices, beginning with [1]:
63
+
64
+
a. Copy the item at that index into a temp variable
65
+
66
+
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
67
+
- Shift items over to the right as you iterate
68
+
69
+
c. When the correct index is found, copy temp into this position
70
+
71
+
#### Your Task
72
+
- Implement the `insertion_sort()` function in the Guided Project with your TA
73
+
74
+
#### Real-World Applications
75
+
The answer to the question, "Is ***Insertion Sort*** an efficient algorithm?" is not always the same. The runtime of ***Insertion Sort*** is dependent on how close to being "in-order" the data is to begin with. In a scenario where you are performing ***Insertion Sort*** on an already or mostly sorted array, very few elements will need to be shifted over, leading to a runtime of Ω(n). However, in a worse-case scenario, where the maximum number of shifts are being performed, the runtime of this algorithm is O(n²).
76
+
51
77
52
78
### Selection Sort
53
79
***Selection Sort*** is an algorithm that many of you have probably used before when sorting things in your everyday lives. Imagine that you have several books you want to arrange on a shelf from shortest to tallest. You start off by looking for the shortest book, and when you find it, put it on the far left side of the shelf. Then, you look for the second shortest book and insert it directly to the right of the first book. You repeat this process, selecting the next shortest book and moving it next to the most recently placed book, until you have moved all books into the correct place. This is ***Selection Sort***.
@@ -102,57 +128,34 @@ While ***Selection Sort*** is one of the easier sorting algorithms to understand
102
128
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*** has a runtime of O(n²), making it impractical to use with many large, real-world data sets.
103
129
104
130
#### Your Task
105
-
- Complete the missing parts of `selection_sort()` in `iterative_sorting.py` with your instructor
106
-
107
-
### Insertion Sort
108
-
Think back to class or team picture day. Everyone stands in a line facing the photographer. Starting at the left-hand side of the line, the photographer checks to make sure each person is taller than the person next to them. If they are shorter, the photographer pulls them out and shifts people over to the right until he or she finds the right spot for this person. They then insert them back into the line. This process repeats until the photographer reaches the last person on the right-hand side, who must be the tallest person in the group. This is ***Insertion Sort***.
109
-
110
-
[(VIDEO) Insert-sort with Romanian folk dance](https://www.youtube.com/watch?v=ROalU379l3U)
131
+
- Complete the missing parts of `selection_sort()` in `iterative_sorting.py`.
111
132
112
-
[](https://www.youtube.com/watch?v=ROalU379l3U)
133
+
### Bubble Sort
134
+
In **Bubble Sort**, we make a series of swaps between adjacent elements, gradually moving larger elements towards the end of the array (or _bubbling_ larger elements up).
113
135
114
136
#### Algorithm
115
-
1. Separate the first element from the rest of the array. Think about it as a sorted list of one element.
116
-
117
-
2. For all other indices, beginning with [1]:
137
+
1. Loop through your array
138
+
- Compare each element to its neighbor
139
+
- If elements in wrong position (relative to each other, swap them)
140
+
2. If no swaps performed, stop. Else, go back to the element at index 0 and repeat step 1.
118
141
119
-
a. Copy the item at that index into a temp variable
142
+
#### Real-World Applications
143
+
***Bubble Sort*** is not ideal for many real-world applications. If a small element that _should_ be at the beginning of our array is originally located near the end, it will take a long time to move it into its correct position.
120
144
121
-
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
122
-
- Shift items over to the right as you iterate
123
-
124
-
c. When the correct index is found, copy temp into this position
145
+
However, it should be noted that if you perform **Bubble Sort** on an array that's already sorted, it will only require a single pass through the array, making its best-case performance linear.
125
146
126
147
#### Your Task
127
-
- Implement the `insertion_sort()` function in `iterative_sorting.py`
128
-
129
-
```
130
-
def insertion_sort():
131
-
# TO BE COMPLETED BY STUDENT
148
+
- Complete `bubble_sort()` in `iterative_sorting.py`.
132
149
133
-
// try it out
134
-
arr = [2,5,9,7,4,1,3,8,6];
135
-
print(arr);
136
-
arr = insertionSort( arr );
137
-
print(arr);
138
-
139
-
```
140
-
141
-
#### Real-World Applications
142
-
The answer to the question, "Is ***Insertion Sort*** an efficient algorithm?" is not always the same. The runtime of ***Insertion Sort*** is dependent on how close to being "in-order" the data is to begin with. In a scenario where you are performing ***Insertion Sort*** on an already or mostly sorted array, very few elements will need to be shifted over, leading to a runtime of Ω(n). However, in a worse-case scenario, where the maximum number of shifts are being performed, the runtime of this algorithm is O(n²).
143
150
144
151
### TO-DO in iterative_sorting.py
145
-
- Complete the missing parts of `selection_sort()`
146
-
- Implement `insertion_sort()` in `iterative_sorting.py`
152
+
- Complete `selection_sort()` and `bubble_sort()`
147
153
148
154
### Stretch Goals
149
155
150
156
#### Try to write a search function
151
157
- Complete the functions in `searching.py`
152
158
153
-
#### Check out Bubble Sort
154
-
- Take a look a the psuedocode for this algorithm and try implementing it in Python.
155
-
156
159
#### There are a few "order n" sorting algorithms whose runtime will be linear, even in a worst case scenario.
157
160
Look into Counting Sort.
158
161
- How is this algorithm different from other iterative sorting algorithms?
@@ -163,7 +166,7 @@ Look into Counting Sort.
163
166
- Explore Bogo Sort and summarize how it works in a couple of sentences.
164
167
165
168
166
-
## Day 2 - A Better Way to Sort
169
+
## Part 3: A Better Way to Sort
167
170
168
171
### Divide & Conquer
169
172
>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.
@@ -180,6 +183,30 @@ Recursive cases *must* be written in a way that will eventually allow us to reac
180
183
181
184
## Recursive Sorting Algorithms
182
185
186
+
### Quick Sort
187
+
Let's think about the group photo example again. Everyone's lined up and the photographer wants to order individuals from shortest to tallest. They pull out the first person from the line and instruct everyone *shorter* than this person to position themselves on the left-hand side. Everyone *taller* than this person is instructed to move to the right-hand side. The photographer then repeats this process with the group of people on the left and the group of people on the right. This is ***Quick Sort***.
188
+
189
+
[(VIDEO) Quick-sort with Hungarian folk dance](https://www.youtube.com/watch?v=ywWBy6J5gz8)
190
+
191
+
[](https://www.youtube.com/watch?v=ywWBy6J5gz8)
192
+
193
+
194
+
#### Algorithm
195
+
```
196
+
1. Select a pivot. Often times this is the first or last element in a set. It can also be the middle.
197
+
2. Move all elements smaller than the pivot to the left.
198
+
3. Move all elements greater than the pivot to the right.
199
+
4. While LHS and RHS are greater than 1, repeat steps 1-3 on each side.
200
+
```
201
+
202
+
### Your Task
203
+
- Implement the `quick_sort()` function in the Guided Project with your TA
204
+
205
+
#### Real-World Applications
206
+
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.
207
+
208
+
209
+
183
210
### Merge Sort
184
211
Your boss asks you to organize an old filing cabinet with 20 years worth of financial documents. He would like things ordered chronologically. You feel overwhelemed. There are thousands of papers in this thing.
185
212
So you decide to break this insane task up into more manageable pieces. First, you focus on organizing a single drawer. But this still has a lot of pieces of data that need to be sorted. Within the drawer, you pull out a single folder. You lay out all the contents on a table, grabbing two pieces at a time, placing the older document on top of the newer one. Then, you start merging sorted sets of documents together until the folder is done. Once all the folders have been reassembled, you order the folders correctly in the drawer. And then you put sorted drawers back into the filing cabinet. This idea of breaking a large set of data down into small pieces, sorting the pieces, then merging them back together is what ***Merge Sort*** is all about.
@@ -198,74 +225,19 @@ So you decide to break this insane task up into more manageable pieces. First, y
198
225
4. Repeat step 3 until the entire data set has been reassembled
199
226
```
200
227
201
-
#### Implementation in Python
202
-
```
203
-
### helper function
204
-
def merge( arrA, arrB ):
205
-
elements = len( arrA ) + len( arrB )
206
-
merged_arr = [ ]
207
-
a = 0
208
-
b = 0
209
-
# since arrA and arrB already sorted, we only need to compare the first element of each when merging!
210
-
for i in range( 0, elements ):
211
-
if a >= len(arrA): # all elements in arrA have been merged
212
-
merged_arr.append(arrB[b])
213
-
b += 1
214
-
elif b >= len(arrB): # all elements in arrB have been merged
215
-
merged_arr.append(arrA[a])
216
-
a += 1
217
-
elif arrA[a] < arrB[b]: # next element in arrA smaller, so add to final array
218
-
merged_arr.append(arrA[a])
219
-
a += 1
220
-
else: # else, next element in arrB must be smaller, so add it to final array
221
-
merged_arr.append(arrB[b])
222
-
b += 1
223
-
return merged_arr
224
-
225
-
226
-
### recursive sorting function
227
-
def merge_sort( arr ):
228
-
if len( arr ) > 1:
229
-
left = merge_sort( arr[ 0 : len( arr ) / 2 ] )
230
-
right = merge_sort( arr[ len( arr ) / 2 : ] )
231
-
arr = merge( left, right ) # merge() defined later
232
-
return arr
233
-
```
234
228
235
229
#### Real-World Applications
236
230
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! *WHY* they do so is because this sorting algorithm is reliably efficient. In all cases, regardless of how sorted the original data set might be, this algorithm will have a runtime of O(n log(n)), one of the better sorting runtimes out there.
237
231
238
232
#### Your Task
239
-
- (STRETCH) Try writing an *in-place****Merge Sort*** algorithm.
240
-
241
-
### Quick Sort
242
-
Let's think about the group photo example again. Everyone's lined up and the photographer wants to order individuals from shortest to tallest. They pull out the first person from the line and instruct everyone *shorter* than this person to position themselves on the left-hand side. Everyone *taller* than this person is instructed to move to the right-hand side. The photographer then repeats this process with the group of people on the left and the group of people on the right. This is ***Quick Sort***.
243
-
244
-
[(VIDEO) Quick-sort with Hungarian folk dance](https://www.youtube.com/watch?v=ywWBy6J5gz8)
245
-
246
-
[](https://www.youtube.com/watch?v=ywWBy6J5gz8)
247
-
248
-
249
-
#### Algorithm
250
-
```
251
-
1. Select a pivot. Often times this is the first or last element in a set. It can also be the middle.
252
-
2. Move all elements smaller than the pivot to the left.
253
-
3. Move all elements greater than the pivot to the right.
254
-
4. While LHS and RHS are greater than 1, repeat steps 1-3 on each side.
255
-
```
233
+
- Implement `merge_sort()` in `recursive_sorting.py`. It's recommended that you use...
234
+
- A recursive function that handles dividing the array (or subarray) in half
235
+
- A helper function that handles merging sorted pieces back together
236
+
-***STRETCH*** - Try writing an *in-place****Merge Sort*** algorithm.
256
237
257
-
#### Your Task
258
-
- Implement the `quick_sort()` function in `recursive_sorting.py`
259
-
```
260
-
def quick_sort(arr):
261
-
# TO BE COMPLETED BY STUDENT
262
-
```
263
-
264
-
#### Real-World Applications
265
-
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.
266
238
267
239
### TO-DO in recursive_sorting.py
268
-
- Implement `quick_sort()` in `recursive_sorting.py`
0 commit comments