Searching Good
Searching Good
Searching Good
Searching
Arrays
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 2
Searching
The process used to find the location of a target
among a list of objects
Searching an array finds the index of first
element in an array containing that value
14 2 10 5 1 3 17 2
Algorithm:
Start with the first array element (index 0)
while(more elements in array){
if value found at current index, return index;
Try next element (increment index);
}
Value not found, return -1;
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 6
1 2 3 5 7 10 14 17
return 0;
}
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 12
Binary Search
Search an ordered array of integers for a value and return
its index if the value is found. Otherwise, return -1.
1 2 3 5 7 10 14 17
6
Copyright © 2000 by Brooks/Cole Publishing Company
A division of International Thomson Publishing Inc.
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 14
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 15
Binary Search
Binary search is based on the “divide-and-
conquer” strategy which works as follows:
Start by looking at the middle element of the
array
– 1. If the value it holds is lower than the search
element, eliminate the first half of the array from
further consideration.
– 2. If the value it holds is higher than the search
element, eliminate the second half of the array from
further consideration.
Repeat this process until the element is found,
or until the entire array has been eliminated.
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 16
Binary Search
Algorithm:
Set first and last boundary of array to be searched
Repeat the following:
Find middle element between first and last boundaries;
if (middle element contains the search value)
return middle_element position;
else if (first >= last )
return –1;
else if (value < the value of middle_element)
set last to middle_element position – 1;
else
set first to middle_element position + 1;
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 17
Binary Search
// Searches an ordered array of integers
int bsearch(int data[], // input: array
int size, // input: array size
int value // input: value to find
) // output: if found,return index
{ // otherwise, return -1
int first, middle, last;
first = 0;
last = size - 1;
while (true) {
middle = (first + last) / 2;
if (data[middle] == value)
return middle;
else if (first >= last)
return -1;
else if (value < data[middle])
last = middle - 1;
else
first = middle + 1;
}
}
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 18
Binary Search
int main() {
const int array_size = 8;
int list[array_size]={1,2,3,5,7,10,14,17};
int search_value;
return 0;
}
COMP102 Prog. Fundamentals: Searching Arrays/ Slide 19
1 2 3 5 7 10 14 17
first mid last
A[0] A[1] A[2]
1 2 3
first mid last
A[2]
In this case,
(first == last)
return -1; 3
fml