CS 105

Week 6

CS 105's
Hunger Games


Solo JavaScript Project
+
Course-Wide Contest


Live Results

CS 105's
Midterm Exam


Next Monday Evening
7:30pm - 9:00pm


(Conflict signups end this Wednesday!)

Puzzle #1

Find the Number 42

Optimal Strategy


  1. Start from the beginning and pick every element

We call this strategy a Linear Search

Puzzle #2

Find the Number 42

Hint: The data is sorted!

Optimal Strategy


  1. Pick a middle element
  2. Remove the half of the data that is no longer relevant
  3. Repeat 1-3 with the remaining data

We call this strategy a Binary Search

Data Linear Search Binary Search
7
_______

_______
15
_______

_______
31
_______

_______
n
_______

_______
1 2 3 4 5 6 7
      *
1 2 3
  *
   3
   *

What is the worst case running time for a binary search with 15 values?

A) 3
B) 4
C) 5
D) 15



  1 2 3 4 5 6 7  8  9 10 11 12 13 14 15

What is the worst case running time for a linear search with 31 values?

A) 3
B) 4
C) 5
D) 31

What is the worst case running time for a binary search with 31 values?

A) 3
B) 4
C) 5
D) 31
Data Linear Search Binary Search
7 7 3
15
_______

_______
31
_______

_______
n
_______

_______
var games = [
  { score: [4, 1],  opponent: "Oakland" },
  { score: [1, 0],  opponent: "Illinois State" },
  { score: [5, 2],  opponent: "TCU" },
  ...
];
Program a Linear Search on JSFiddle

Sorting

var data =
[ 50, 34, 87, 13, 11, 58, 17, 29, 58 ];

A Sorting Strategy


  1. Find the smallest value in the data
  2. Swap the smallest value with the first element
    (now the first value is sorted)
  3. Repeat (1)-(3) with the remaining data

We call this strategy a Selection Sort

// 1: Find the lowest value
[ 50, 34, 87, 13, 11, 58, 17, 29, 58 ]


// 2: Swap with the first
[ 11, 34, 87, 13, 50, 58, 17, 29, 58 ]


// 3: Repeat, ignoring the sorted part
[ 11, 34, 87, 13, 50, 58, 17, 29, 58 ]
[ 50, 34, 87, 13, (11), 58, 17, 29, 58 ]
[ 11, 34, 87, 13,  50 , 58, 17, 29, 58 ]










Data Linear Search Binary Search Selection Sort
9
_______

_______

_______
100
_______

_______

_______
n
_______

_______

_______
var games = [
{ score: [4, 1],  opponent: "Oakland" },
{ score: [1, 0],  opponent: "Illinois State" },
{ score: [5, 2],  opponent: "TCU" },
...
];
Program a Binary Search on JSFiddle