-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursionBinarySearch.c
More file actions
35 lines (30 loc) · 836 Bytes
/
RecursionBinarySearch.c
File metadata and controls
35 lines (30 loc) · 836 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int key)
{
if (low > high)
return -1;
int mid = low+(high-low)/2;
if (arr[mid] == key)
return mid; // Key found
else if (arr[mid] > key)
return binarySearch(arr, low, mid-1, key);
else
return binarySearch(arr, mid+1, high, key);
}
int main() {
int n, key;
printf("Enter size of array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements in ascending order:\n", n);
for (int i=0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter element to search: ");
scanf("%d", &key);
int result = binarySearch(arr, 0, n-1, key);
if (result == -1)
printf("Element not found.\n");
else
printf("Element found at location %d.\n", result);
return 0;
}