Lectures12-part-09-algorithms-1

Howmanystepsdoesittakewhenlinearsearchisrun

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: … M(n) Input x; Find memory location i such that M(i)=x (or report that x is not in list) Linear_search (x) i = 0 WHILE i < n+1 IF M(i) = x then halt and output i ELSE i = i+1 Output “not in the list”. How many steps does it take when Linear_search is run? Binary Search Binary Search Assume sorted data M(0) … M(n) Binsearch (x) put left, right fingers on 0 and n let midpoint be the point halfway between. WHILE x not equal M(midpoint) IF M(midpoint) < x THEN move left finger to midpoint ELSE move right finger to midpoint set midpoint halfway between fingers END WHILE Binary Search Binary Search Assume sorted data M(0) … M(n) Binsearch (x) left = 0 right = n midpoint = (left + right) / 2 WHILE x notequal M(midpoint) IF M(midpoint) < x THEN left = midpoint ELSE right = midpoint midpoint = (left + right) / 2 END WHILE This actually has several bugs. Can you figure out what they are? stepping through binary search stepping through binary search left right midpoint Initial values 0 16 ? compute midpt 0 16 8 move left 8 16 8 compute midpt 8 16 12 move right 8 12 12 compute midpt 8 12 10 move right 8 10 10 compute midpt 8 10 9 ARRAY M( ) searching for 33 M(0) = 3 M(1) = 4 M(2) = 6 M(3) = 21 M(4) = 24 M(5) = 27 M(6) = 28 M(7) = 30 M(8) = 31 M(9) = 33 M(10)= 39 M(11)= 44 M(12)= 4...
View Full Document

This document was uploaded on 04/02/2014.

Ask a homework question - tutors are online