Binary Search on String Array - C Data Structure

C examples for Data Structure:Search

Description

Binary Search on String Array

Demo Code

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

#define MaxNameSize 14//from ww  w  .  j  a  v a  2 s  .  c  o m

#define MaxNameBuffer MaxNameSize+1

#define MaxNames 8
int binarySearch(int lo, int hi, char key[], int max, char list[MaxNames][MaxNameBuffer]) {
  while (lo <= hi) {
    int mid = (lo + hi) / 2;
    int cmp = strcmp(key, list[mid]);
    if (cmp == 0) return mid; // found
    if (cmp < 0) hi = mid - 1;
    else lo = mid + 1;
  }
  return -1; //lo and hi have crossed; key not found
}
int main() {

  int n;
  char name[MaxNames][MaxNameBuffer] = { "A","D","K","O", "R","S", "S", "T" };

  n = binarySearch(0, 7, "A", MaxNameBuffer, name);
  printf("%d\n", n);

  n = binarySearch(4, 7, "O", MaxNameBuffer, name);
  printf("%d\n", n);

  n = binarySearch(0, 7, "S", MaxNameBuffer, name);
  printf("%d\n", n);
}

Related Tutorials