Binary and Sequential Searching
Binary and Sequential Searching
Searching
Searching
the process used to find the location of a target among a list
of objects.
Basic Searching Methods for Arrays
Sequential search
Binary search
Sequential search
normally used when a list is not sorted
it starts at the beginning of the list and searches
until it finds the data or hits the end of the list
in a sorted list, the search terminates when the
target is less than the current element.
Sequential Search Algorithm
1. looker = 0
2. loop (looker < last AND target not equal list[looker])
1. looker = looker + 1
3. end loop
4. location = looker
5. if (target equal list[looker])
1. found = true
6. else
1. found = false
7. end if
8. return found
Figure 2-4: Binary search example.
Figure 2-5
1. First = 0
2. Last = end
3. Loop (first <= last)
1. Mid = (first + last)/2
2. If (target > list[mid])
Look in the upper half
First = mid + 1
3. Else if (target < list[mid])
Look in the lower half
1. Last = mid – 1
4. Else
5. Found equal : force exit
1. First = last + 1
6. End if
4. End loop
5. Locn = mid
6. If (target equal list[mid])
1. Found = true
7. Else
1. Found = false
8. End if
9. Return found
1. First = 0, Last = list.size() - 1
2. while (first <= last)
1. Mid = (first + last)/2
2. If (list[mid] < target])
Look in the upper half
First = mid + 1
3. Else if (target < list[mid])
Look in the lower half
1. Last = mid – 1
4. Else
1. Return mid
5. End if
3. End loop
4. Return -1
Binary Search
Exercise 1 / page 74
8 13 17 26 44 56 88 97
Loop # First Mid Last Compare
1 0 3 (26) 7 88 > 26
2 4 5 (56) 7 88 > 56
3 6 6 (88) 7 88 = 88
final 8 6 (88) 7
8 13 17 26 44 56 88 97