Slip 23 - B) Write a ‘C’ program to create a random array of n integers. Accept a value x from user and use Binary search algorithm to check whether the number is present in array or not. (Students can accept sorted array or can use any sorting method to sort the array)

Solution:

#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements:\n");
scanf("%d",&n);
printf("Enter %d integers :\n", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find :\n");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high) {
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key) {
printf("%d found at location %d.", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list.", key);
return 0;
}

Post a Comment

0 Comments