Monday 10 March 2014

BINARY SEARCH

DESCRIPTION:-

A Binary search algorithm finds the position of a specified input value within an array sorted by key value. In each step, the algorithm compares the search key value with the key value at the middle value . If the keys matches , then the search key is found and its position is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub array to the left of the middle element or, if the search key is greater, on the sub-array to the right, If the remaining array to be searched is empty, then the key cannot be found in the array and  a special "not found" indication is retuned.

OPERATION:-

Binary_Search(int str[5], int element)
this function has array and element to be searched as its parameters. This function performs the binary search to find the position of element.

ALGORITHM:-

Binary_Search(int str[5], int element)
1) low <--- 0
2) high<---max-1
3) found<---0
4) repeat till low<=high
5) mid<---(low + high)/2
6) if str[mid]=element
7) then found<---1 and break
8) if str[mid]>element
9) then high=mid-1
10)else low=mid+1;
11)if found=1
12)then  print element found at position mid+1
13)else print element not found
14)end

PROGRAM CODE:-

#include<stdio.h>
#include<conio.h>
Binary_Search(int str[5], int element)
{
int low=0;
int high=4;
int mid;
int found=0;
while(low<=high)
{
mid=(low+ high)/2;
if(str[mid]==element)
{
found=1;
break;
}
if(str[mid]>element)
high=mid-1;
else
low=mid+1;
}
if(found==1)
printf("\n Element is found at position : %d", mid+1);
else
printf("\n Element is not found");
}
void main()
{
int str[5],i;
int element=0;
clrscr();
printf("Enter 5 elements :");
for(i=0;i<5;i++)
scanf("%d", &str[i]);
printf("\n Enter element to be searched : ");
Binary_Search(int str[5], int element) 
getch();
}
 

 OUTPUT:-

Enter 5 elements :
1
2
3
4
5
 Enter element to be searched : 3
 Element is found at position : 3

 

No comments:

Post a Comment