Sei sulla pagina 1di 17

Chapter 2

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

It needs to tell the calling algorithm . . .


1. Find the data it was looking for;
2. What index are the target data found.
It requires four parameters.
 List we are searching.
 Index to the last element in the list (or size).
 The target.
 The address where the found element’s index
location is to be stored.
Figure 2-1: Locating data in unordered list
Figure 2-2: Search concept
Figure 2-3: Unsuccessful search in unordered list.
The 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

An array contains the elements shown below. Using the


binary search algorithm, trace the steps followed to find 88.
At each loop iteration, including the last, show the contents
of first, last, and mid.

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

locn = 6 (88), found = true


Table 1 Solution to Chapter 2, Exercise 1.
Exercise 2 / page 74

An array contains the elementsshown below. Using the


binary search algorithm, trace the steps followed to find 20.
At each loop iteration, including the last, show the contents
of first, last, and mid.

8 13 17 26 44 56 88 97

Potrebbero piacerti anche