/* Binary Searching in an array. */
#include <stdio.h>
int main()
{
int n, i, item, pos = -1;
printf("Enter the elements of array: ");
scanf("%d", &n);
int a[n], beg, mid, end;
for(i = 0; i < n; i++){
printf("Enter element %d: ", i+1);
scanf("%d", &a[i]);
}
printf("The array you entered is .....\n");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nEnter the element whose position you want: ");
scanf("%d", &item);
beg = 0;
end = n-1;
binary:
if(beg <= end){
mid = (beg+end)/2;
if(a[mid] == item)
pos = mid + 1;
else if (a[mid] > item){
end = mid-1;
goto binary;
}
else{
beg = mid + 1;
goto binary;
}
}
if(pos == -1)
printf("Value is not founded.\n");
else
printf("%d is founded at position %d.\n", item, pos);
return 0;
}
Comments
Post a Comment