### CS62 - Spring 2011 - Lecture 8

- how did the lab go?
- assignment 2 is out
- start on it now
- it's going to be more difficult than the last
- Prof Bruce will be running a special session on Monday at 7:30 pm in Edmunds 227 (the other lab)
- example output is online
- your table should look like this one
- your output will likely be different since you're randomly sampling
- keep looking at the written homework problems posted

• Insertion sort
- what is the basic approach for sorting used by insertion sort?
- last time, we "proved" it was correct
- loop invariant
- prove by induction
- book has lots more detail on all of the algorithms (read it! :)
- run-time of insertion sort
- multiple different cases depending on the input
- often want to talk about three cases:
- best case
- worst case
- average case
- what are these for insertion sort and when do they happen?
- best case: O(n) linear
- each time we get to the inner while loop, we find that "current" is already in the correct location
- when it's reverse sorted
- each time in the inner while loop, we have to traverse all the way to the beginning of the array
- on average, we'll have to traverse through half of the sorted list to insert "current"
- will be faster than the worse case (by about a factor of 2), but still O(n^2)

• Merge sort
- Say I give you two piles of cards that I tell you are both sorted. I want you to merge them into a single sorted list, however, you may only look at two cards at a time, one from each stack. How could you do this efficiently?
- This idea is the key idea behind MergeSort
- If we had a "merge" method, how could we use it to sort a list of numbers?
- how could we use this method to sort two numbers?
- can we repeat this idea?
- what is the runtime?
- look at the layers
- each layer processes n items
- how many layers are there?
- each time we split the data in half
- 2^i = n
- log(n) levels
- O( n log n )

• Quicksort: see slides (ppt)

• Built-in sorting
- Arrays.sort(Object[] a) -- uses merge sort
- Collections.sort(List list) -- uses quicksort