You are on page 1of 3

School of Computing Science and Engineering

VIT Bhopal University

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.

To write and execute C++ program to perform Linear Search.

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.

Name: Bhavesh Kushwaha [1] Regd. Number: 22MCA10023


School of Computing Science and Engineering
VIT Bhopal University

A. If true return MID value.


B. If above condition isn’t true then it will check for one more condition, middle
value of Array is less than Target value or not i.e.{ A[mid]<target } –
i. If above condition is TRUE then update lo value to (middle value + 1).
ii. Else update hi value to (middle value – 1).

Example:

Program Code:

#include<iostream>
using namespace std;

int bsSearch(int arr[],int n,int key){


    int s=0;
    int e=n;
    while(s<=e){
        int mid=(s+e)/2;

        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];

Name: Bhavesh Kushwaha [2] Regd. Number: 22MCA10023


School of Computing Science and Engineering
VIT Bhopal University

    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.

Name: Bhavesh Kushwaha [3] Regd. Number: 22MCA10023

You might also like