Professional Documents
Culture Documents
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
• Algorithm:
• 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
first17mid last
A[6] A[7]
In this case,
(data[middle] == value) 14
return middle;
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
first17
mid last
A[4]
In this case,
(first == last)
return -1;
fml
7
Example: binary search