-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy path1-binary_recursive.c
54 lines (48 loc) · 1.66 KB
/
1-binary_recursive.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
52
53
54
#include "search_algos.h"
/**
* binary_search_recursive - Searches recursively for a value in a sorted
* array of integers using binary search.
* @array: A pointer to the first element of the [sub]array to search.
* @left: The starting index of the [sub]array to search.
* @right: The ending index of the [sub]array to search.
* @value: The value to search for.
*
* Return: If the value is not present, -1.
* Otherwise, the index where the value is located.
*
* Description: Prints the [sub]array being searched after each change.
*/
int binary_search_recursive(int *array, size_t left, size_t right, int value)
{
size_t i;
if (right < left)
return (-1);
printf("Searching in array: ");
for (i = left; i < right; i++)
printf("%d, ", array[i]);
printf("%d\n", array[i]);
i = left + (right - left) / 2;
if (array[i] == value)
return (i);
if (array[i] > value)
return (binary_search_recursive(array, left, i - 1, value));
return (binary_search_recursive(array, i + 1, right, value));
}
/**
* binary_search - Searches for a value in a sorted array
* of integers using binary search.
* @array: A pointer to the first element of the array to search.
* @size: The number of elements in the array.
* @value: The value to search for.
*
* Return: If the value is not present or the array is NULL, -1.
* Otherwise, the index where the value is located.
*
* Description: Prints the [sub]array being searched after each change.
*/
int binary_search(int *array, size_t size, int value)
{
if (array == NULL)
return (-1);
return (binary_search_recursive(array, 0, size - 1, value));
}