CS51A - Spring 2019 - Class 37

Example code in this lecture

   sorting.py

Lecture notes


  • admin
       - midterm 3
          - average: 15.5 (82%)
          - median: 15.75 (83%)

       - no lab today
          - office hours from 2-3pm

  • Sorting
       Input: A list of numbers nums
       Output: The list of numbers in sorted order, i.e. nums[i] <= nums[j] for all i < j

       - cards
          - sort cards: all cards in view
          - sort cards: only view one card at a time
       - many different ways to sort a list

  • Selection sort
       - high-level:
          - starting from the beginning of the list and working to the back, find the smallest element in the remaining list
             - in the first position, put the smallest item in the list
             - in the second position, put the next smallest item in the list
             - ...
          - to find the smallest item in the remaining list, simply traverse it, keeping track of the smallest value

       - look at selection_sort in sorting.py code
          - What is the running time of selection sort?
             - We'll use the variable n to describe the length of the array/input
             - How many times do we go through the for loop in selectionSort?
                - n times
             - Each time through the for loop in selectionSort, we find the smallest element. How much work is this?
                - first time, n-1, second, n-2, third, n-3 ...
                - O(n)
             - what is the overall cost for selectionSort?
                - we go through the for loop n times
                - each time we go through the for loop we incur a cost of roughly n
                - O(n^2)
       
  • Insertion sort
       - high-level: starting from the beginning of the list and, working towards the end, keep the list items we've seen so far in sorted order. For each new item, traverse the list of things sorted already and insert it in the correct place.
       - look at insertion_sort function in sorting.py code
          - what is the running time?
             - How many times do we iterate through the while loop?
                - in the best case: no times
                   - when does this happen?
                      - when the list is sorted already
                   - what is the running time? linear, O(n)
                - in the worst case: j - 1 times
                   - when does this happen?
                   - what is the running time?
                      - \sum_{j=1}^n-1 j = ((n-1)n)/2
                      - O(n^2)
                - average case: (j-1)/2 times
                   - O(n^2)