Given a list or array of elements (usually of uniform type)
Return:
Post-Condition: after the function, the list is sorted:
Imagine you have the following unsorted list:
[ 30 | 10 | 3 | 45 | 50 | 100 | 0 ]
How would you go about sorting it?
It is one of the fundamental problems in computer science, with many solutions
Comparison Sort
Non-comparison sort
Bogo sort: Orders a list of values by repetitively shuffeling them and checking if they are sorted.
Name comes from “bogus”
What is the runtime?
\(O(N^2)\) algorithms:
\(O(N^{1.5})\) algorithm: Shell Sort
\(O(N \log N)\) algorithms:
\(O(N)\) algorithm: radix sort
You have 10 minutes to complete the quiz
Check ONE option (zero will be awarded to quizzes with multiple answers checked)
Approach: “select” item for each location and swap:
Mid search snapshot:
Nested loops:
small variable in between the outer and the inner loop to hold the smallest value indexsmall with the current index at inner iteration, updating small whenever a smaller value is found)Swapping in place:
lst[i], lst[small] = lst[small], lst[i]
def selection_sort(lst):
for i in range(len(lst) - 1):
# Find index of smallest
small = i
for j in range(i + 1, len(lst)):
if lst[j] < lst[small]:
small = j
# Swap smallest into place
lst[i],lst[small] = lst[small],lst[i]
if __name__ == "__main__":
fruit = ["blackberry", "apple", "papaya", "cantaloupe", "apricot", "banana"]
selection_sort(fruit)
print(fruit)['apple', 'apricot', 'banana', 'blackberry', 'cantaloupe', 'papaya']
What’s Selection Sort’s runtime?
What’s Selection Sort’s runtime?
\(O(N^2)\)
Approach: While the list is not sorted, iterate through the list swaping adjacent pairs.
Animation of what Bubble Sort looks like
Called “bubble” sort because large numbers bubble to the “top” (end of the list)
Mid search snapshot:
Nested loops:
Swapping in place:
lst[j], lst[j+1] = lst[j+1], lst[j]
How do we know a list is sorted? If there were not swaps, the list is sorted.
What’s Bubble Sort’s runtime?
What’s Bubble Sort’s runtime?
\(O(N^2)\)
Approach: Keep two zones, a sorted and unsorted zone. “Insert” next element into sorted zone
Mid Search snapshot:
Nested loops:
Swapping in place:
lst[j], lst[j-1] = lst[j-1], lst[j]
What’s Insertion Sort’s runtime?
What’s Insertion Sort’s runtime?
\(O(N^2)\)