|
| 1 | +#include "search_algos.h" |
| 2 | + |
| 3 | +/** |
| 4 | + * _binary_search - Searches for a value in a sorted array |
| 5 | + * of integers using binary search. |
| 6 | + * @array: A pointer to the first element of the array to search. |
| 7 | + * @left: The starting index of the [sub]array to search. |
| 8 | + * @right: The ending index of the [sub]array to search. |
| 9 | + * @value: The value to search for. |
| 10 | + * |
| 11 | + * Return: If the value is not present or the array is NULL, -1. |
| 12 | + * Otherwise, the index where the value is located. |
| 13 | + * |
| 14 | + * Description: Prints the [sub]array being searched after each change. |
| 15 | + */ |
| 16 | +int _binary_search(int *array, size_t left, size_t right, int value) |
| 17 | +{ |
| 18 | + size_t i; |
| 19 | + |
| 20 | + if (array == NULL) |
| 21 | + return (-1); |
| 22 | + |
| 23 | + while (right >= left) |
| 24 | + { |
| 25 | + printf("Searching in array: "); |
| 26 | + for (i = left; i < right; i++) |
| 27 | + printf("%d, ", array[i]); |
| 28 | + printf("%d\n", array[i]); |
| 29 | + |
| 30 | + i = left + (right - left) / 2; |
| 31 | + if (array[i] == value) |
| 32 | + return (i); |
| 33 | + if (array[i] > value) |
| 34 | + right = i - 1; |
| 35 | + else |
| 36 | + left = i + 1; |
| 37 | + } |
| 38 | + |
| 39 | + return (-1); |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * exponential_search - Searches for a value in a sorted array |
| 44 | + * of integers using exponential search. |
| 45 | + * @array: A pointer to the first element of the array to search. |
| 46 | + * @size: The number of elements in the array. |
| 47 | + * @value: The value to search for. |
| 48 | + * |
| 49 | + * Return: If the value is not present or the array is NULL, -1. |
| 50 | + * Otherwise, the index where the value is located. |
| 51 | + * |
| 52 | + * Description: Prints a value every time it is compared in the array. |
| 53 | + */ |
| 54 | +int exponential_search(int *array, size_t size, int value) |
| 55 | +{ |
| 56 | + size_t i = 0, right; |
| 57 | + |
| 58 | + if (array == NULL) |
| 59 | + return (-1); |
| 60 | + |
| 61 | + if (array[0] != value) |
| 62 | + { |
| 63 | + for (i = 1; i < size && array[i] <= value; i = i * 2) |
| 64 | + printf("Value checked array[%ld] = [%d]\n", i, array[i]); |
| 65 | + } |
| 66 | + |
| 67 | + right = i < size ? i : size - 1; |
| 68 | + printf("Value found between indexes [%ld] and [%ld]\n", i / 2, right); |
| 69 | + return (_binary_search(array, i / 2, right, value)); |
| 70 | +} |
0 commit comments