-
-
Save ehudthelefthand/37c86adcc174fc39dd2b7dca5cc5f869 to your computer and use it in GitHub Desktop.
Simple Binary Search
This file contains 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> | |
#include <stdlib.h> | |
// or int *a | |
int binary_search(int a[], int x, int left, int right) { | |
if (left > right) return -1; | |
int mid = (left + right) / 2; | |
if (a[mid] == x) return mid; | |
if (x < a[mid]) return search(a, x, left, mid - 1); | |
else return search(a, x, mid + 1, right); | |
} | |
char **search(int a[], int x, int left, int right) { | |
int result = binary_search(a, x, left, right); | |
return result == -1 ? "Not Found :(" : "Found :D"; | |
} | |
int main() { | |
int n; | |
scanf("%d", &n); | |
int a[n]; | |
for (int i = 0; i < n; i++) { | |
scanf("%d", &a[i]); | |
} | |
printf("Search for %d: %s \n", 10, search(a, 10, 0, n - 1)); | |
printf("Search for %d: %s \n", 20, search(a, 20, 0, n - 1)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment