Skip to content

Instantly share code, notes, and snippets.

@avii-7
Created September 1, 2021 05:31
Show Gist options
  • Save avii-7/3ccf6cd0ea8860154cfd2c93cbd689fb to your computer and use it in GitHub Desktop.
Save avii-7/3ccf6cd0ea8860154cfd2c93cbd689fb to your computer and use it in GitHub Desktop.
Write a C program for binary search.
#include <stdio.h>
int search(int *, int, int, int);
int main()
{
int arr[] = {2, 4, 8, 16, 32, 64, 128, 256};
int size = sizeof(arr) / sizeof(arr[0]);
int find = 128;
printf("%d is found at Array index: %d.", find, search(arr, 0, (size - 1), find));
return 0;
}
int search(int *arr, int start, int end, int x)
{
while (start <= end)
{
int mid = (start + end) / 2;
if (arr[mid] == x)
return mid;
else if (arr[mid] > x)
end = mid - 1;
else
start = mid + 1;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment