0% found this document useful (0 votes)
17 views2 pages

Fourth

Uploaded by

abcd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views2 pages

Fourth

Uploaded by

abcd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

AIM: Write a C program to implement binary search.

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:

Step 1: Find the middle element of array. using,


middle = initial_value + end_value / 2;
Step 2: If middle = element, return ‘element found’ and index.
Step 3: if middle > element, call the function with end_value = middle - 1.
Step 4: if middle < element, call the function with start_value = middle + 1.
Step 5: exit.

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:

You might also like