-
Notifications
You must be signed in to change notification settings - Fork 0
/
104-advanced_binary.c
54 lines (48 loc) · 1.74 KB
/
104-advanced_binary.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"
/**
* advanced_binary_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 advanced_binary_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 && (i == left || array[i - 1] != value))
return (i);
if (array[i] >= value)
return (advanced_binary_recursive(array, left, i, value));
return (advanced_binary_recursive(array, i + 1, right, value));
}
/**
* advanced_binary - Searches for a value in a sorted array
* of integers using advanced 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 first index where the value is located.
*
* Description: Prints the [sub]array being searched after each change.
*/
int advanced_binary(int *array, size_t size, int value)
{
if (array == NULL || size == 0)
return (-1);
return (advanced_binary_recursive(array, 0, size - 1, value));
}