Session Thirty Eight

advertisement
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
3
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
After each run, one more high card is in order
Lower cards slowly “bubble” to the bottom
4
Bubble Sort

See sortingAlgorithms.py
5
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
6
Big O

In fact, the big O of the other sorts we will talk
about today is also n2!
7
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
8
Insertion Sort

See sortingAlgorithms.py
9
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
10
Selection Sort

See sortingAlgorithms.py
11
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
12
Sorting Complexity


All these algorithms are approximately n2
Can we do better?
13
Download