Binary Search Integers
Binary Search 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