Skip to content

Instantly share code, notes, and snippets.

@theoctober19th
Last active May 21, 2020 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theoctober19th/d745052762c493b99a2b272603f5152e to your computer and use it in GitHub Desktop.
Save theoctober19th/d745052762c493b99a2b272603f5152e to your computer and use it in GitHub Desktop.
Code Golf Binary Search
#define i int
#define x return
i b(i*a,i k,i l,i r){i m=(l+r)/2;x a[m]==k?m:l>=r?-1:k<a[m]?b(a,k,l,m-1):b(a,k,m+1,r);}
@theoctober19th
Copy link
Author

Here is the program to test the function.

#include<stdio.h>
int main(){
  int arr[] = {4, 6, 7, 8, 9, 12};
  int key = 12;
  int i = b(arr, key, 0, sizeof(arr) / sizeof(arr[0]));
  if(i==-1) printf("Key doesn't exist");
  else printf("Key exists at index %d", i);
  return 0;
}

@isarojdahal
Copy link

#include<stdio.h>
int main(){
int arr[] = {4, 6, 7, 8, 9, 12},key = 12, i = b(arr, key, 0, sizeof(arr) / sizeof(arr[0]));
(i==-1)? printf("Key doesn't exist"):printf("Key exists at index %d", i);
return 0;
}

@theoctober19th
Copy link
Author

#include<stdio.h>
int main(){
int arr[] = {4, 6, 7, 8, 9, 12},key = 12, i = b(arr, key, 0, sizeof(arr) / sizeof(arr[0]));
(i==-1)? printf("Key doesn't exist"):printf("Key exists at index %d", i);
return 0;
}

you need to optimize the function, not the driving code 😆 Try to shorten the original binary_search.c file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment