Programming Examples

Cpp program to search an element in a sorted array using function


write a program to search(binary)an element in an array using function

Solution

#include<iostream>
using namespace std;
int Bsearch(int[],int,int);
int main(){
    int arr[50],ITEM,index,n;
    cout<<"Enter the desired array size";
    cin>>n;
    cout<<"Enter the elements";
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    cout<<"Enter the element to be searched for :";
    cin>>ITEM;
    index=Bsearch(arr,n,ITEM);
    //cout<<" Index is: "<< index;
    if(index==-1)
    {
        cout<<" Element cannot be found"<<endl;
    }
    else
    {
        cout<<"Element found at index "<<index<<",position "<<index+1<<endl;
        return 0;
    }
   
}
int Bsearch(int arr[],int size, int item)
{
    int upper,lower=0,mid;
     upper=size-1;
    while(lower<=upper)
    {
        mid=(upper+lower)/2;
        if(item==arr[mid])
        {
            return mid;
        }
        else if(item<arr[mid])
        {
            upper=mid-1;
        }
        else
        {
            lower=mid+1;
        }
    }
    return -1;
}
Output

Enter the desired array size 

10

Enter the elements(Sorted in ascending order) 

2

3

5

9

12

15

20

23

25

30

Enter the element to be searched for :20

Element found at index 6 position 7

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz