Intro to Computer Science CS1510 Dr. Sarah Diesburg More Sorting Intro to Computer Science CS1510 Dr. Sarah Diesburg
Summary What have we done so far? Refreshed ourselves on definition of algorithm Searches Linear and binary Big O notation Sorts
Sorting Methods Bubble Sort Higher elements “bubble” to the end Compare two elements Move the lower element to the left Look at the next element Repeat Higher elements “bubble” to the end After each run, one more high element is in order Lower elements slowly “bubble” to the bottom
Bubble Sort See sortingAlgorithms.py
Big O of the Bubble Sort Roughly how many comparisons do we make with the bubble sort in the worst case Roughly n comparisons over n times = n2 What is this saying? As n grows, the time the algorithm takes grows by roughly a square Example: As you double your data, you quadruple your time
Big O In fact, the big O of the other sorts we will talk about today is also n2!
Sorting Methods Insertion Sort Two chunks of data (sorted and unsorted) Go through unsorted data and insert it in order into sorted part of the list As humans, if we could look at all elements at once, we would probably perform an insertion sort
Insertion Sort See sortingAlgorithms.py
Quicksort We won’t be looking at the code, because it needs something called recursion to run We don’t have time to introduce this Instead, let’s think generally about how it works
Quicksort Pick a middle element Place all elements lower than the middle partition into one list Place all elements higher than the partition into another list Repeat with lists until lists are small Sort small lists with bubble or insertion sort Merge sorted lists back together
Sorting Humans will tend to want to fan out all the elements (things to sort) and scan them With small numbers, this works But what if I gave you 10,000 student ID cards? Computers can only compare a finite number of elements together at a time