-
Notifications
You must be signed in to change notification settings - Fork 466
/
BinarySearchRecursion.c
51 lines (40 loc) · 1.32 KB
/
BinarySearchRecursion.c
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
int binarySearchRecursive(int arr[], int left, int right, int target, int *counter) {
(*counter)++;
if (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
return binarySearchRecursive(arr, mid + 1, right, target, counter);
} else {
return binarySearchRecursive(arr, left, mid - 1, target, counter);
}
}
return -1;
}
int main() {
int size;
printf("Enter the size of the sorted array: ");
if (scanf("%d", &size) != 1 || size <= 0) {
printf("Invalid input for size. Please enter a positive integer.\n");
return 1;
}
int array[size];
printf("Enter %d elements in sorted order for the array:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
int target;
printf("Enter the target value to search for: ");
scanf("%d", &target);
int counter = 0;
int result = binarySearchRecursive(array, 0, size - 1, target, &counter);
if (result != -1) {
printf("Target %d found at index %d\n", target, result);
} else {
printf("Target %d not found in the array\n", target);
}
printf("Total comparisons made: %d\n", counter);
return 0;
}