Wednesday 18 March 2015

Program to search an element using binary search Using C


# include <stdio.h>
# include <conio.h>
void main()
{
int a[10], f, l, i, j, k, mid, n, t, flag = 0 ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the elements :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(i = 0 ; i < n ; i++)
for(j = i + 1 ; j < n ; j++)
if(a[i] > a[j])
{
t = a [i] ;
a[i] = a[j] ;
a[j] = t ;
}
printf("\nThe ordered elements are : \n\n") ;
for(i = 0 ; i < n ; i++)
printf("%d\t", a[i]) ;
printf("\n\nEnter the element to be searched : ") ;
scanf("%d", &k) ;
f = 0 ;
l = n - 1 ;
while(f <= l)
{
mid = (f + l) / 2 ;
if(a[mid] == k)
{
flag = 1 ;
break ;
}
else if(a[mid] < k)
f = mid + 1 ;
else
l = mid - 1 ;
}
if(flag == 1)
printf("\nThe element is found at location : %d", mid + 1) ;
else
printf("\nThe element is not found") ;
getch() ;
}


RUN 1 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The ordered elements are :
10 20 30 40 50
Enter the element to be searched : 30
The element is found at location : 3

RUN 2 :
~~~~~~~
Enter the limit : 5
Enter the elements :
20 40 30 50 10
The ordered elements are :
10 20 30 40 50
Enter the element to be searched : 70
The element is not found

No comments:

Post a Comment