*This preview shows
page 1. Sign up
to
view the full content.*

**Unformatted text preview: **5
M(13)= 48
M(14)= 50
M(15)= 55
M(16)= 57 Running Times
Running Times
Binary Search At each iteration, range is cut in half
Total number of iterations to find an item among N elements is y such that “cut N in half y times to get down to 1”
Yes, this is just (base 2) log N
Searching among 2300 elements takes only 300 steps (this exceeds the number of particles in the universe!!) Linear search vs. Binary search
Linear search vs. Binary search Sorting Algorithms
Sorting Algorithms Different methods to put things in order Which are fastest methods? Bubble Sort
Bubble Sort
Put left, right fingers on M(0), M(1)
IF M(left) > M(right) THEN swap them
Move left, right fingers to right
IF right finger = n
THEN done with this pass, start again BUT next time only go up to n1
Etc., for passes ending at n2, n3, etc. Aside: FOR loops
Aside: FOR loops new kind of iteration command (similar to WHILE)
Example
FOR i = 1 to 10
Outputs 3,6,9,…,30 print 3*i
Example
FOR count = 100 downto 1 print count
Outputs 100,99,98,…,1 Bubble Sort
Bubble Sort
FOR max = n1 downto 1
make a pass up to position max
FOR left = 1 upto max
right = left + 1
IF M(left) > M(right) THEN swap them LET’S UNROLL THIS CODE TO MAKE SURE WE UNDERSTAND Bubble Sort
Bubble Sort
FOR max = n1 downto 1
FOR left = 1 upto max
right = left + 1
IF M(left) > M(right) THEN swap them
Let max = n1 blah blah blah
Let max = n2 blah blah blah
… etc
Let max = 2 blah blah blah
Let max = 1 blah blah blah make a pass up to p...

View
Full
Document