Program to search an element using binary search
Program:
#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();
}
Output:
Case: 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
Case: 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
-
UpdatedDec 31, 2019
-
Views6,570
You May Like
Program to maintain employee details using structures
Program to maintain student details using structures
Check whether the person is eligible to vote or not
Print the numbers that are divisible by a given no.
Program to generate magic square
To sort the given numbers in ascending & descending order