- Home
- Course Category
- Course Result
- Course Detail
Hot Line: 0124-2383121
Course Introduction
Programs for practice
In the program below, we've introduced beginers to programming in C++
Source Code: Implement Binary Search
/* C++ Program - Binary Search (Data structure using C)*/
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, arr[50], search, first, last, middle;
cout<<"Enter total number of elements :";
cin>>n;
cout<<"Enter "<<n<<" number :";
for (i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter a number to find :";
cin>>search;
first = 0;
last = n-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < search)
{
first = middle + 1;
}
else if(arr[middle] == search)
{
cout<<search<<" found at location "<<middle+1<<"\n";
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<"Not found! "<<search<<" is not present in the list.";
}
getch();
}
Output
Enter total number of elements : 5
Enter 5 number: 1 4 7 8 9
Enter a number to find: 7
7 found at location 3