Fourth
Fourth
THEORY: This search algorithm works on the principle of divide and conquer. For this algorithm
to work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection. If a
match occurs, then the index of item is returned. If the middle item is greater than the item, then
the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched
for in the sub-array to the right of the middle item. This process continues on the sub-array as well
until the size of the subarray reduces to zero.
ALGORITHM:
CODE:
#include<stdio.h>
int Binary_search(int arr[], int first, int last, int x) {
if (last >= 1) {
int mid = first + (last - 1) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return Binary_search(arr, first, mid - 1, x);
return Binary_search(arr, mid + 1, last, x);
}
return -1;
}
int main(){
int num,i;
printf("Enter number of elements : ");
scanf("%d",&num);
int Arr[num];
for(i=0;i<num;i++){
printf("Enter Arr[%d] : ",i+1);
scanf("%d",&Arr[i]);
}
int ele;
printf("Enter element to be searched : ");
scanf("%d",&ele);
int n = sizeof(Arr) / sizeof(Arr[0]);
int result = Binary_search(Arr,0,n-1,ele);
(result == -1) ? printf("Element is not present in array\n") : printf("Element is present at index %d \n",result);
return 0;
}
OUTPUT: