-
Notifications
You must be signed in to change notification settings - Fork 0
/
1-binary.c
39 lines (34 loc) · 962 Bytes
/
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
#include "search_algos.h"
/**
* 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)
{
size_t i, left, right;
if (array == NULL)
return (-1);
for (left = 0, right = size - 1; right >= left;)
{
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)
right = i - 1;
else
left = i + 1;
}
return (-1);
}