CS 46B - Lecture 10

Cover page image

Pre-class reading

Two Golden Rules for Pseudocode

  1. Each pseudocode statement corresponds to one or a small number of Java statements
  2. Each pseudocode statement can be unambigously translated to Java

Selection Sort

  1. Find the smallest and swap it with the first element
    5 9 17 11 12

  2. Find the next smallest. It is already in the correct place
    5 9 17 11 12

  3. Find the next smallest and swap it with first element of unsorted portion
    5 9 11 17 12

  4. Repeat
    5 9 11 12 17

  5. When the unsorted portion is of length 1, we are done
    5 9 11 12 17

Selection Sort on Various Size Arrays*

n Seconds
10,000 0.786
20,000 2.148
30,000 4.796
40,000 9.192
50,000 13.321
60,000 19.299

* Obtained with a Pentium processor, 2 GHz, Java 6, Linux

Selection Sort on Various Size Arrays

Lecture 10 Clicker Question 1

On that particular machine, how long would it take to sort an array of 100,000 elements?

  1. About 8 seconds
  2. About 26 seconds
  3. About 53 seconds
  4. About 100 seconds

Analyzing the Performance of the Selection Sort Algorithm

Analyzing the Performance of the Selection Sort Algorithm

Analyzing the Performance of the Selection Sort Algorithm

Lecture 10 Clicker Question 2

How long would it take to sort an array of 1,000,000 elements?

  1. About 10 times as long as sorting an array of 10,000 elements
  2. About 100 times as long as sorting an array of 10,000 elements
  3. About 1000 times as long as sorting an array of 10,000 elements
  4. About 10,000 times as long as sorting an array of 10,000 elements

Lecture 10 Clicker Question 3

Here is the Albanian sort algorithm:

Randomly shuffle the array
Check if it is sorted
If not, repeat

What is the big-oh complexity?

  1. O(n2)
  2. O(2n)
  3. O(nn)
  4. None of the above

Big-Oh Isn't Just for Sorting

Finding the Most Frequent Element

Big-Oh of Most Frequent Element

Lecture 10 Clicker Question 4

Maybe it's better to sort the array first? Then identical elements are next to each other, and you can find the most frequent one in a single pass through the sorted array. What is the big-Oh efficiency of that, assuming that we use selection sort for the sorting?

  1. O(n)
  2. O(n2 + n)
  3. O(n2)
  4. O(n3)