A c program that carries out binary search of an element entered by the user in an array of elements and then displace the location of that element else if not found it displace element not found.
#include <stdio.h>
int main()
{
int i,j,c, first, last, middle, n, search,temp;
int elements[100];
printf("Enter number of elements: ");
scanf("%d", &n);
for (c = 0; c < n; c++){
printf("Enter integer number %d: ",c);
scanf("%d", &elements[c]);
}
for(i = 0 ; i < n - 1; i++)
{
for(j = 0 ; j < n-i-1; j++)
{
if(elements[j] > elements[j+1])
{
temp=elements[j];
elements[j]=elements[j+1];
elements[j+1]=temp;
}
}
}
printf("Sorted numbers:\n");
for (c = 0; c < n; c++){
printf("%d ",elements[c]);
}
printf("\n\nEnter value to search: ");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (elements[middle] < search)
first = middle + 1;
else if (elements[middle] == search) {
printf("%d found at location %d.\n", search, middle);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
getchar();
getchar();
return 0;
}
Comments
Leave a comment