exercism

Exercism solutions.
git clone git://code.dwrz.net/exercism
Log | Files | Refs

binary_search.c (641B)


      1 #include <stdio.h>
      2 #include "binary_search.h"
      3 
      4 int* binary_search(int val, int arr[], int len) {
      5 	if (arr == NULL) return NULL;
      6 	if (len == 0) return NULL;
      7 
      8 	// Base case -- we found the value.
      9 	if (arr[len/2] == val) {
     10 		return &arr[len/2];
     11 	}
     12 
     13 	// The middle value is smaller than our search.
     14 	// Recurse into the upper half of the array.
     15 	if (arr[len/2] < val) {
     16 		return binary_search(val, &arr[len/2] + 1, len/2);
     17 	}
     18 
     19 	// The middle value is larger than our search.
     20 	// Recurse into the lower half of the array.
     21 	if (arr[len/2] > val) {
     22 		return binary_search(val, arr, len/2);
     23 	}
     24 
     25 	return NULL; // We weren't able to find the value.
     26 }