Search Algo
Search Algo
Search Algo
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;
Unordered Linear Search
// Searches an unordered array of integers
int search(int data[], //input: array
int size, //input: array size
int value){ //input: search value
// output: if found, return index;
// otherwise, return –1.
for(int index = 0; index < size; index++){
if(data[index] == value)
return index;
}
return -1;
}
Ordered Linear Search
• Search an ordered array of integers for a value
and return its index if the value is found;
Otherwise, return -1.
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
1 2 3 5 7 10 14 17
• Algorithm:
1 2 3 5 7 10 14 17
• Binary search skips over parts of the array if the search value
cannot possibly be there.
6
Copyright © 2000 by Brooks/Cole Publishing Company
A division of International Thomson Publishing Inc.
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;
Iterative Binary Search
int binarySearch(int arr[], int n, int x)
{ int l, r, m;
l=0; r=n-1;
while (l <= r) {
int m = l + (r-l)/2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was not present
return -1;
}
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;
}
}
Example: binary search
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
• 14 ? 1 2 3 5 7 10 14 17
first mid last
A[4] A[5] A[6] A[7]
7 10 14 17
first mid last
A[6] A[7]
In this case,
(data[middle] == value)
return middle;
14 17
f mid last
Example: binary search
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
• 8? 1 2 3 5 7 10 14 17
first mid last
A[4] A[5] A[6] A[7]
7 10 14 17
first mid last
1 2 3
first mid last
A[2]
In this case, (first
== last)
return -1; 3
fml
Efficiency of Binary Search