Wednesday, March 11, 2020

Program of Binary Search in C++

// Binary Search

#include<iostream>
using namespace std;

int binary(int arr[], int size, int item){

    int beg = 0, last = size - 1, mid;
 
while (beg <= last){
   
    mid = (beg + last) / 2;
   
    if (arr[mid] == item)
    return mid;
else if (item > arr[mid])
beg = mid + 1;
else
last = mid - 1;
}
return -1;
}


int main(){

int size, item, output;

cout<<"\nEnter Size of Array : ";
cin>>size;
int arr[size];

cout<<"\nEnter "<<size<<" Elements : ";
for(int i=0;i<size;i++){
cin>>arr[i];
}

cout<<"\nEnter Element to Search : ";
cin>>item;
output = binary(arr,size,item);

if(output != -1)
cout<<"\nElement "<<item<<" Found at index "<<output;
else
cout<<"\nElement Not Found !";

return 0;
}


No comments:

Post a Comment