Skip to content

Commit 0aabdfe

Browse files
committed
Fix merge conflicts
2 parents 2cc9e84 + 54d9504 commit 0aabdfe

5 files changed

Lines changed: 79 additions & 156 deletions

File tree

‎.DS_Store‎

6 KB
Binary file not shown.

‎project/iterative_sorting.py‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Complete the selection_sort() function below in class with your instructor
1+
# TO-DO: Complete the selection_sort() function below
22
def selection_sort( arr ):
33
# loop through n-1 elements
44
for i in range(0, len(arr) - 1):
@@ -18,13 +18,7 @@ def selection_sort( arr ):
1818
return arr
1919

2020

21-
# TO-DO: implement the Insertion Sort function below
22-
def insertion_sort( arr ):
23-
24-
return arr
25-
26-
27-
# STRETCH: implement the Bubble Sort function below
21+
# TO-DO: implement the Bubble Sort function below
2822
def bubble_sort( arr ):
2923

3024
return arr

‎project/recursive_sorting.py‎

Lines changed: 6 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,16 @@
1-
### helper function
1+
# TO-DO: complete the helpe function below to merge 2 sorted arrays
22
def merge( arrA, arrB ):
33
elements = len( arrA ) + len( arrB )
44
merged_arr = [0] * elements
5-
a = 0
6-
b = 0
7-
# since arrA and arrB already sorted, we only need to compare the first element of each when merging!
8-
for i in range( 0, elements ):
9-
if a >= len(arrA): # all elements in arrA have been merged
10-
merged_arr[i] = arrB[b]
11-
b += 1
12-
elif b >= len(arrB): # all elements in arrB have been merged
13-
merged_arr[i] = arrA[a]
14-
a += 1
15-
elif arrA[a] < arrB[b]: # next element in arrA smaller, so add to final array
16-
merged_arr[i] = arrA[a]
17-
a += 1
18-
else: # else, next element in arrB must be smaller, so add it to final array
19-
merged_arr[i] = arrB[b]
20-
b += 1
5+
# TO-DO
6+
217
return merged_arr
228

239

24-
### recursive sorting function
10+
# TO-DO: implement the Merge Sort function below USING RECURSION
2511
def merge_sort( arr ):
26-
if len( arr ) > 1:
27-
left = merge_sort( arr[ 0 : len( arr ) // 2 ] )
28-
right = merge_sort( arr[ len( arr ) // 2 : ] )
29-
arr = merge( left, right ) # merge() defined later
12+
# TO-DO
13+
3014
return arr
3115

3216

@@ -42,12 +26,6 @@ def merge_sort_in_place(arr, l, r):
4226
return arr
4327

4428

45-
# TO-DO: implement the Quick Sort function below USING RECURSION
46-
def quick_sort( arr, low, high ):
47-
48-
return arr
49-
50-
5129
# STRETCH: implement the Timsort function below
5230
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
5331
def timsort( arr ):

‎project/tests.py‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,17 +44,6 @@ def test_selection(self):
4444
self.assertEqual(selection_sort(arr2), [])
4545
self.assertEqual(selection_sort(arr3), [0,1,2,3,4,5])
4646

47-
48-
def test_insertion(self):
49-
arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
50-
arr2 = []
51-
arr3 = [0, 1, 2, 3, 4, 5]
52-
53-
self.assertEqual(insertion_sort(arr1), [0,1,2,3,4,5,6,7,8,9])
54-
self.assertEqual(insertion_sort(arr2), [])
55-
self.assertEqual(insertion_sort(arr3), [0,1,2,3,4,5])
56-
57-
5847
# def test_bubble(self):
5948
# arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
6049
# arr2 = []
@@ -99,15 +88,5 @@ def test_merge(self):
9988
# self.assertEqual(merge_sort_in_place(arr4, 0, len(arr4)-1), [0,1,2,3,4,5])
10089

10190

102-
def test_quick(self):
103-
arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
104-
arr2 = []
105-
arr3 = [0, 1, 2, 3, 4, 5]
106-
107-
self.assertEqual(quick_sort(arr1, 0, len(arr1)-1), [0,1,2,3,4,5,6,7,8,9])
108-
self.assertEqual(quick_sort(arr2, 0, len(arr2)-1), [])
109-
self.assertEqual(quick_sort(arr3, 0, len(arr3)-1), [0,1,2,3,4,5])
110-
111-
11291
if __name__ == '__main__':
11392
unittest.main()

‎readme.md‎

Lines changed: 71 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
# Sorting Algorithms
22
*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.*
33

4-
## Day 1 - Why Is It So Important to Sort Data?
4+
## Part 1: Why is it So Important to Sort Data?
55

66
### We're Always Searching
77
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.
88

99
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.
1010

1111
### 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.
1313

1414
#### Linear (Sequential) Search
1515

@@ -47,7 +47,33 @@ While the justification for *WHY* we want to sort our data is pretty clear, a ha
4747

4848
[Just for fun...(VIDEO) 15 Sorting Algorithms in 6 Minutes ![alt text](https://i.ytimg.com/vi/kPRA0W1kECg/maxresdefault.jpg)](https://www.youtube.com/watch?v=kPRA0W1kECg)
4949

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+
[![(VIDEO) Insert-sort with Romanian folk dance](https://i.ytimg.com/vi/ROalU379l3U/hqdefault.jpg)](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+
5177

5278
### Selection Sort
5379
***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
102128
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.
103129

104130
#### 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`.
111132

112-
[![(VIDEO) Insert-sort with Romanian folk dance](https://i.ytimg.com/vi/ROalU379l3U/hqdefault.jpg)](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).
113135

114136
#### 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.
118141

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.
120144

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.
125146

126147
#### 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`.
132149

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²).
143150

144151
### 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()`
147153

148154
### Stretch Goals
149155

150156
#### Try to write a search function
151157
- Complete the functions in `searching.py`
152158

153-
#### Check out Bubble Sort
154-
- Take a look a the psuedocode for this algorithm and try implementing it in Python.
155-
156159
#### There are a few "order n" sorting algorithms whose runtime will be linear, even in a worst case scenario.
157160
Look into Counting Sort.
158161
- How is this algorithm different from other iterative sorting algorithms?
@@ -163,7 +166,7 @@ Look into Counting Sort.
163166
- Explore Bogo Sort and summarize how it works in a couple of sentences.
164167

165168

166-
## Day 2 - A Better Way to Sort
169+
## Part 3: A Better Way to Sort
167170

168171
### Divide & Conquer
169172
>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
180183

181184
## Recursive Sorting Algorithms
182185

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+
[![(VIDEO) Quick-sort with Hungarian folk dance](https://i.ytimg.com/vi/ywWBy6J5gz8/hqdefault.jpg)](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+
183210
### Merge Sort
184211
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.
185212
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
198225
4. Repeat step 3 until the entire data set has been reassembled
199226
```
200227

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-
```
234228

235229
#### Real-World Applications
236230
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.
237231

238232
#### 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-
[![(VIDEO) Quick-sort with Hungarian folk dance](https://i.ytimg.com/vi/ywWBy6J5gz8/hqdefault.jpg)](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.
256237

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.
266238

267239
### TO-DO in recursive_sorting.py
268-
- Implement `quick_sort()` in `recursive_sorting.py`
240+
- Implement the `merge_sort()`
269241

270242
### Stretch Goals
271243

0 commit comments

Comments
 (0)