Created
September 1, 2021 05:31
-
-
Save avii-7/3ccf6cd0ea8860154cfd2c93cbd689fb to your computer and use it in GitHub Desktop.
Write a C program for binary search.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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