Skip to content

Instantly share code, notes, and snippets.

@outlinepix
Created August 15, 2022 15:49
Show Gist options
  • Save outlinepix/a026ed2cb4f7d5f228d1d8ffb0e7e549 to your computer and use it in GitHub Desktop.
Save outlinepix/a026ed2cb4f7d5f228d1d8ffb0e7e549 to your computer and use it in GitHub Desktop.
Binary search for list of integers in C using recursion .
#include <stdio.h>
int binarySearch(int[], int, int, int);
int main()
{
/* Basic condition for binary search is list must be sorted or you have some kinda machanism to sort it */
int array[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int length = sizeof(array) / sizeof(array[0]);
int target = 30;
int index = binarySearch(array, 0, length - 1, target);
(index == -1) ? printf("Element not found.\n") : printf(" Element %d found at %d index.\n", target, index);
return 0;
}
int binarySearch(int array[], int beginIndex, int endingIndex, int target)
{
if (beginIndex > endingIndex) /* Not found */
return -1;
int middle = (beginIndex + endingIndex) / 2;
if (array[middle] == target)
{
return middle;
}
else if (target > array[middle])
{
return binarySearch(array, middle + 1, endingIndex, target);
}
else
{
return binarySearch(array, beginIndex, middle - 1, target);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment