Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

Program of Binary Search in Array

This C++ program demonstrates binary search in an array. It prompts the user to enter the size of an integer array, then populates the array with sorted elements. It asks the user to input an element to search for, calls a binary search function passing the array, size and search item. The function returns the index of a matching element or -1 if not found. It prints the result.

Uploaded by

Suman Lata
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Program of Binary Search in Array

This C++ program demonstrates binary search in an array. It prompts the user to enter the size of an integer array, then populates the array with sorted elements. It asks the user to input an element to search for, calls a binary search function passing the array, size and search item. The function returns the index of a matching element or -1 if not found. It prints the result.

Uploaded by

Suman Lata
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

/*PROGRAM OF BINARY SEARCH IN ARRAY*/

#include<iostream.h> #include<conio.h> int Bsearch(int[],int,int); void main() { int AR[50],ITEM,N,Index; clrscr(); cout<<"Enetr desired Array size(max.50):"; cin>>N; cout<<"\nEnter Array Elements(must be sorted in asc. order)\n"; for(int i=0;i<N;i++) cin>>AR[i];

{ }

cout<<"\nEnter Element to be searched for..."; cin>>ITEM; Index=Bsearch(AR,N,ITEM); if(Index==-1) cout<<"\nSorry given element could not be found.\n"; else cout<<"\nElement found at Index:"<<Index<<",Position:"<<Index+1<<endl; } int Bsearch(int AR[],int size,int item) { int beg,last,mid; beg=0; last=size-1; while(beg<=last) {mid=(beg+last)/2; if(item==AR[mid]) return mid; else if(item>AR[mid]) beg=mid+1; else last=mid-1; } return -1; }

OUTPUT
Enetr desired Array size(max.50):5 Enter Array Elements(must be sorted in asc. order) 1 2 3 4 5 Enter Element to be searched for2 Element found at Index:1, Position:2

You might also like