Source: Tenor.com
Comparison with linear search:
Binary search | Linear search | |
---|---|---|
efficiency | Efficient for large lists | Efficient for small lists |
Requirement | Requires sorted list | No need to sort |
Average case for 10 records | 3 comparisons | 5 comparisons |
Average case for 1000 records | 10 comparisons | 500 comparisons |
Average case for 10000 records | 14 comparisons | 5000 comparisons |
left = 1
right = n
mid = integral of (left + right) / 2
while left <= right and arr[mid] != target // exit when target is found (Case 1)
if target < arr[mid] // target < middle (Case 2)
right = mid - 1
else // target > middle (Case 3)
left = mid + 1
mid = integral of (left + right) / 2
#include <iostream>
using namespace std;
int main(){
int arr[] = {13, 24, 35, 46, 57, 68, 79, 90, 101, 112};
int n = 10, target, left, right, mid, flag = 0;
left = 0;
right = n - 1;
mid = (left + right) / 2;
cout << "Enter the target value: ";
cin >> target;
// binary search here
// output result
if (flag == 1)
cout << "Target value found at index " << mid << endl;
else
cout << "Target value not found" << endl;
}