
1
CSCI 100
Think Like Computers
Lecture 23
Fall 2008
Last Time ā¦
ā¢Lists (arrays)
ā¢Implementing algorithms
ā¢Sequential search
ā¢Binary search
Binary Search
ā¢binarySearch(list, target) returns index (if found) or -1
ā¢[āCharlieā, āDaveā, āJackā, āJeraldā, āJerrollā, āLauraā,
āLoisā, āWinnieā]
ā¢Use 3 index variables
īleft: the leftmost range index (inclusive)
īright: the rightmost range index (exclusive)
īmid: the middle index for the range (left, right)
ā¢Some things to remember:
īleft < right : the range contains value
īOtherwise, nothing Ćsearch fail
How Do We Implement It?
ā¢[āCharlieā, āDaveā, āJackā, āJeraldā, āJerrollā,
āLauraā, āLoisā, āWinnieā]
ā¢Compare array[mid] with target
īIf equal, we found it Ćreturn mid
īOtherwise, we shrink the range and starts with the
new left, right, mid values (another iteration of the
loop)
īarray[mid] > target : right = mid
īarray[mid] < target : left = mid+1;
īNew mid : Math.floor(( left + right )/2), as always
Example
ā¢[āCharlieā, āDaveā, āJackā, āJeraldā,
āJerrollā, āLauraā, āLoisā, āWinnieā]
ā¢Search for āZoeā:
ā¢left right mid list[mid]
ā¢1st try 0 8 4 Jerroll
ā¢2nd try 5 8 6 Lois
ā¢3rd try 7 8 7 Winnie
ā¢4th try 8 8 Ćno values, return -1
Exercise
ā¢[āCharlieā, āDaveā, āJackā, āJeraldā,
āJerrollā, āLauraā, āLoisā, āWinnieā]
ā¢Search for āJonesā:
ā¢left right mid list[mid]
ā¢1st try
ā¢2nd try
ā¢3rd try
ā¢ā¦