Professional Documents
Culture Documents
Binary Search (DSA)
Binary Search (DSA)
Ex.No.2
Binary Search
14.09.2022
AIM:
Binary search is an efficient algorithm for finding an item from a sorted list of items. It works
by repeatedly dividing in half the portion of the list that could contain the item, until you've
narrowed down the possible locations to just one.
Pseudocode:
BinarySearch(A, target):
1. lo = 0
2. hi = len(A) - 1
3. while lo <= hi:
4. mid = (lo + hi) / 2
5. if A[mid] == target:
6. return mid
7. elif
A[mid] < target:
lo = mid + 1
8. else:
hi = mid - 1
Explanation:
1. Initialize lo variable as 0.
2. Initialize hi variable = (length of ARRAY – 1).
3. Check whether lo is less than or equal to hi value or Not.
A. If above condition is true it will enter in LOOP and execute further statements of
that loop.
B. Otherwise, it will not enter in LOOP and proceed to other statements.
4. Sum lo and hi and divide sum by 2.
5. Check whether mid value of given ARRAY is Equal to Target or not.
Example:
Program Code:
#include<iostream>
using namespace std;
if(arr[mid]==key){
return mid;
}
else if(arr[mid]>key){
e=mid-1;
}
else{
s=mid+1;
}
}
return -1;
}
int main(){
freopen("input.txt","r",stdin);
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int key;
cin>>key;
cout<<bsSearch(arr,n,key)<<endl;
return 0;
Output Screenshots:
RESULT:
Thus, the programs for the given problem statements has been executed and the results are
verified successfully.