Use the binary search technique. - C Data Structure

C examples for Data Structure:Search

Description

Use the binary search technique.

Demo Code

#include <stdio.h>

int binarysearch(int * arr, int arr_size, int target);

int binarysearch_aux(int * arr, int target, int low, int high);

int binarysearch(int * arr, int arr_size, int target){
  return binarysearch_aux(arr, target, 0, arr_size - 1);
}

int binarysearch_aux(int * arr, int target, int low, int high){
  // base case//from w  w  w.ja  va  2 s  .c  om
  if (low == high)
    return arr[low] == target ? 1 : 0;
  // recursion case
  else {
    int mid = (low + high) / 2;
    if (arr[mid] < target)
      return binarysearch_aux(arr, target, mid + 1, high);
    else
      return binarysearch_aux(arr, target, low, mid);
  }
}

int main(void){

  int arr[10] = {1, 4, 6, 9, 11, 12, 15, 19, 25, 40};

  for (int i = 0; i < 15; i++)
  {
    printf("%d in array? %s\n", i, binarysearch(arr, 10, i) ? "yes" : "no");
  }
}

Result


Related Tutorials