-
Notifications
You must be signed in to change notification settings - Fork 0
/
1-binary.c
82 lines (73 loc) · 2.36 KB
/
1-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
#include "search_algos.h"
/**
* binary_search - function that searches for array value in array sorted array
* of integers using Binary search algorithm.
* @array: pointer to the first element of the array to search in.
* @size: number of elements in array.
* @value: value to search for.
*
* You can assume that array will be sorted in ascending order
* You can assume that value won’t appear more than once in array.
* If value is not present in array or if array is NULL return -1.
*
* Return: the index where value is located.
*/
int binary_search(int *array, size_t size, int value)
{
return (binary_search_helper(array, 0, size - 1, value));
}
/**
* binary_search_helper - recursive helper function for binary_search.
* @array: pointer to the first element of the array to search in.
* @l: left index of array.
* @r: right index of array.
* @value: value to look for.
*
* You can assume that value won’t appear more than once in array.
* If value is not present in array or if array is NULL return -1.
*
* Return: the index where value is located.
*/
int binary_search_helper(int *array, size_t l, size_t r, int value)
{
int mid;
/* if l is ever > r, it means the element is not in the array */
if (!array || l > r)
return (-1);
print_array(array, l, r);
/* find the mid-way index between index l and index r */
mid = l + (r - l) / 2;
if (l == r)
return (*(array + mid) == value ? (int)mid : -1);
/* if we've found the element at the mid-way index, return the index */
if (array[mid] == value)
return (mid);
/**
* else if the element MUST be in the left-portion of the portion of the
* array we are currently looking at, search for it in this portion
*/
else if (array[mid] > value)
return (binary_search_helper(array, l, mid - 1, value));
/**
* else if the element MUST be in the right-portion of the portion of the
* array we are currently looking at, search for it in this portion
*/
else
return (binary_search_helper(array, mid + 1, r, value));
}
/**
* print_array - Prints an array of integers.
* @array: The array to be printed.
* @l: The left index of the array.
* @r: The right index of the array.
*/
void print_array(int *array, size_t l, size_t r)
{
size_t i;
if (array)
{
printf("Searching in array: ");
for (i = l; i < l + (r - l + 1); i++)
printf("%d%s", *(array + i), i < l + (r - l) ? ", " : "\n");
}
}