-
Notifications
You must be signed in to change notification settings - Fork 17
/
104-advanced_binary.c
104 lines (87 loc) · 2.05 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "search_algos.h"
int recursive_binary_search(int *array, int left, int right, int value);
void print_search(int *array, int first, int last);
/**
* advanced_binary - Searches value in array using the Binary search algo
*
* @array: Array to search
*
* @size: Size of the array
*
* @value: Value to search
*
* Return: First index where value is located or -1 for NULL array
*/
int advanced_binary(int *array, size_t size, int value)
{
/* Check inputs and call recursive search return value */
if (array && size)
{
return (recursive_binary_search(array, 0, (int)size - 1, value));
}
/* Otherwise return -1 */
return (-1);
}
/**
* recursive_binary_search - Recursively breaks array into subarrays & searches
*
* @array: Array to search
*
* @left: Search on left side of array
*
* @right: Search on right side of array
*
* @value: Value to search
*
* Return: First index where value is located or -1 for NULL array
*/
int recursive_binary_search(int *array, int left, int right, int value)
{
int middle;
/* If value is smaller then middle, look in first half of array */
if (right >= left)
{
middle = left + (right - left) / 2;
print_search(array, left, right);
/* If search finds value in middle, return value */
if (array[left] == value)
{
return (left);
}
/* If element is less than middle, search left subarray */
if (array[middle] < value)
{
return (recursive_binary_search(array, middle + 1, right, value));
}
/* Otherwise search for value in right subarray */
return (recursive_binary_search(array, left, middle, value));
}
/* If element doesn't exist return -1 */
return (-1);
}
/**
* print_search - Prints arrayand side of array
*
* @array: Array to search
*
* @first: left hand side of array
*
* @last: right hand side of array
*
* Return: Void
*/
void print_search(int *array, int first, int last)
{
int index = 0;
printf("Searching in array: ");
while (first <= last)
{
if (index > 0)
{
printf(", ");
}
index = first++;
printf("%d", array[index++]);
}
printf("\n");
}