0% found this document useful (0 votes)
40 views4 pages

Binary Search

This C++ program implements binary search on an array. It takes user input for the array size and elements, sorts the array, performs a binary search to find a target value, and outputs whether it was found along with the iteration and comparison counts. It uses pointers to track the first, middle, and last index to search between on each iteration, narrowing the range until the target is found or the range is exhausted.

Uploaded by

Mohd Haider
Copyright
© © All Rights Reserved
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)
40 views4 pages

Binary Search

This C++ program implements binary search on an array. It takes user input for the array size and elements, sorts the array, performs a binary search to find a target value, and outputs whether it was found along with the iteration and comparison counts. It uses pointers to track the first, middle, and last index to search between on each iteration, narrowing the range until the target is found or the range is exhausted.

Uploaded by

Mohd Haider
Copyright
© © All Rights Reserved
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/ 4

/* BINARY SEARCH */

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int list[100];
int i,j,n,pos,x;
int first,middle,last,temp,ci,cc;
ci=cc=0;
clrscr();
cout<<"\nEnter the size of list: ";
cin>>n;
cout<<"\nEnter the Elements of the Array\n";
for(i=0;i<n;i++)
cin>>list[i];
first=0;
pos=-1;
last=n-1;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(list[j]>list[j+1])
{
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
}
}
}

clrscr();
cout<<"\nNo.s entered are:\n";
for(i=0;i<n;i++)

cout<<list[i]<<" ";
cout<<"\n\n\nEnter the Value to be searched: ";
cin>>x;
while((first<=last)&&(pos==-1))
{
ci++;
middle=(first+last)/2;
cc++;
if(list[middle]==x)
{
pos=middle;
}
else
{
cc++;
if(list[middle]<x)
{
first=middle+1;
}
else
{
last=middle-1;
}
}
}
if(pos>-1)
{
cout<<"\n\nElement found at position:"<<++pos;
cout<<"\nInteration counter:"<<ci;
cout<<"\nComparison counter:"<<cc;
}

else
cout<<"\n\nSearch Unsuccessfull!!";
getch();
}

OUTPUT
Successful Search
Enter the size of list: 5
Enter the Elements of the Array
22
54
23
12
10
No.s entered are:
10 12 22 23 54
Enter the Value to be searched: 22
Element found at position:3
Interation counter:1
Comparison counter:1

Unsuccessful Search
Enter the size of list: 5
Enter the Elements of the Array
23
11
67
323
5
No.s entered are:
5 11 23 67 323
Enter the Value to be searched:10
Search Unsuccessfull!!
Interation counter:3
Comparison counter:6

You might also like