0% found this document useful (0 votes)
9 views2 pages

Binary Search Integers

The document outlines an algorithm and program for implementing binary search on integers. It details the steps for reading input, searching for a key element in a sorted array, and providing output based on the search result. The program is implemented in C and includes example runs demonstrating successful and unsuccessful searches.

Uploaded by

spiderman.macz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Binary Search Integers

The document outlines an algorithm and program for implementing binary search on integers. It details the steps for reading input, searching for a key element in a sorted array, and providing output based on the search result. The program is implemented in C and includes example runs demonstrating successful and unsuccessful searches.

Uploaded by

spiderman.macz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

4.

Implement Binary Search on Integers

Algorithm:

Step 1: Start
Step 2: Read the number of elements ‘n’
Step 3: Read ‘n’ elements in ascending order to the array ‘a’
Step 4: Read the ‘key’ element to be searched.
Step 5: Initialise low = 0 and high = n-1
Step 6: while( low <= high)
do
mid=( low+high)/2
if(key = = a[mid])
flag=1
break;
end if
if(key > a[mid])
low=mid+1
else
high=mid-1
end if-else
end of while
Step 7: if(flag = =1)
Output Successful search and the position of the element found
else
Output unsuccessful search
end of if-else
Step 6: Stop
Program:

#include <stdio.h>
int main() {
int n,i,a[10],key,low,high,mid,flag=0;
printf("\n Enter the no. of elements : ");
scanf("%d",&n);
printf("\n Enter %d elements in ascending order ",n);
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);
printf("\n Enter the key element to search : ");
scanf("%d",&key);
low = 0;
high = n-1;
while(low <= high)
{
mid=(low+high)/2;
if(key==a[mid])
{
flag=1;
break;
}
if(key > a[mid])
low=mid+1;
else
high = mid-1;
}
if(flag==1)
printf("\n Successful Search. Element found in position %d", mid+1);
else
printf("\n Unsuccessful Search");
return 0;
}

Output:
First Run:
Enter the no. of elements : 5
Enter 5 elements in ascending order: 10 20 30 40 50
Enter the key element to search : 40
Successful Search. Element found in position 4
Second Run:
Enter the no. of elements : 6
Enter 5 elements in ascending order: 11 24 33 46 50 62
Enter the key element to search : 29
Unsuccessful Search

You might also like