Skip to content

Instantly share code, notes, and snippets.

@jaredgrady
Last active April 10, 2017 15:35
Show Gist options
  • Save jaredgrady/f660ab4fa9ae82778f6156744b86fa8f to your computer and use it in GitHub Desktop.
Save jaredgrady/f660ab4fa9ae82778f6156744b86fa8f to your computer and use it in GitHub Desktop.
Binary search a list of ints. Recursive implementation in Python.
def bin_search(L, a):
if (len(L) == 1):
return "NO"
mid = len(L) // 2
if (a < L[mid]):
return bin_search(L[:mid], a)
elif (a > L[mid]):
return bin_search(L[mid:], a)
else:
return "YES"
def main():
a = int(input('Search for: '))
L = [1,3,5,7,12,18,22,38]
print(bin_search(L, a))
main()
@CreaturePhil
Copy link

In C:

#include <string.h>
#include <stdio.h>

int binarysearch(int *nums, int n)
{
  int low, high, mid;

  low = 0;
  high = sizeof(nums);

  while (low <= high)
  {
    mid = (low + high) / 2;
    if (nums[mid] > n)
      high = mid - 1;
    else if (nums[mid] < n)
      low = mid + 1;
    else
      return mid;
  }

  return -1;
}


int main()
{
  int nums[] = {1,2,3,5,34,45,56,7};
  int index0 = binarysearch(nums, 34);
  int index1 = binarysearch(nums, -34);
  printf("%d\n", index0);
  printf("%d\n", index1);
  return 0;
}

@jaredgrady
Copy link
Author

Nice work 👍

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