A Simple Binary Search for Integers

BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { mid = low + ((high - low) / 2) if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid // found }//while end return -1 // not found }

To implement Generic Binary Search

– Comparison must be based upon Data type of Input.

– to get Data type of Input

– sizeof( )

Eg:

#define TYPE(x)( sizeof(x) == sizeof(integer) ? return integer: sizeof(x) == sizeof(character) ? return char: sizeof(x) == sizeof(double)) ? return double : )

– Make function to compare according to size.

Compare (A[mid] , value) { if(TYPE(A[mid] != TYPE(value)) return null; if ( TYPE( A[mid] == integer ){ //Simple comparison and return } if ( TYPE( A[mid] == character ){ // Compare with User Defined which function which checks for lexicographic order. //See Void CompareLexo() } }// Compare Void CompareLexo(){ //pseudo code to understand logic. const char* string = "Bac"; int c = strcmp(string, "Bca"); //c will be <= -1 int c = strcmp(string, "B"); //c will be >=1 }

The same way you can think for Double , Structure etc Input and create your code.

**PS : Please comment/mail us perfect running code or better logic**