Skip to content

Commit f422d2a

Browse files
santhoshsamy29t2013anurag
authored andcommitted
Added binary search in C (#1166)
1 parent d8ddcd9 commit f422d2a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

binary_search/c/binary_search.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include<stdio.h>
2+
3+
int binarySearch(int arr[], int l, int r, int x)
4+
{
5+
if (r >= l)
6+
{
7+
int mid = l + (r - l)/2;
8+
9+
if (arr[mid] == x) return mid;
10+
11+
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
12+
13+
return binarySearch(arr, mid+1, r, x);
14+
}
15+
return -1;
16+
}
17+
18+
int main(void)
19+
{
20+
int arr[10],i,x;
21+
printf("Enter the elements of the array : \n");
22+
for(i=0 ; i<10 ; i++){
23+
scanf("%d",&arr[i]);
24+
}
25+
int n = sizeof(arr)/ sizeof(arr[0]);
26+
printf("Enter the element to be searched : \n");
27+
scanf("%d",&x);
28+
int result = binarySearch(arr, 0, n-1, x);
29+
(result == -1)? printf("Element is not present in array")
30+
: printf("Element is present at index %d", result);
31+
return 0;
32+
}

0 commit comments

Comments
 (0)