Intro to Computer Science CS1510 Dr. Sarah Diesburg More Sorting Intro to Computer Science CS1510 Dr. Sarah Diesburg
Any Questions Lab? Programming assignment?
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 cards “bubble” to the top Compare two cards Move the higher card to the top Pick out another card Repeat Higher cards “bubble” to the top After each run, one more high card is in order Lower cards 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 pile As humans, if we could look at all cards at once, we would probably perform an insertion sort
Insertion Sort See sortingAlgorithms.py
Sorting Methods Selection Sort Find smallest card by Comparing two cards at a time Saving out the current smallest card Repeat until reach end of pile Put smallest card in sorted pile Repeat
Selection Sort See sortingAlgorithms.py
Sorting Humans will tend to want to fan out all the cards and scan them With 13 cards, this works But what if I gave you 10,000 student ID cards? Computers can only compare a finite number of cards together at a time
Sorting Complexity All these algorithms are approximately n2 Can we do better?