I need to write a template for binary search routine so that it works with arrays of various types (int, char, c style strings). Here is how I have it written,it seems to work when I have a interger array but fails on chars. I need help fixing this.
Binary Search Routine:
template <typename Type>
int rBinarySearch(Type sortedArray[], int first, int last, Type key, int (*compare)(const void* a, const void* b))
{
Type *keyPtr;
keyPtr=&key;
if (first <= last) {
int mid = (first + last) / 2; // compute mid point.
Type *midPtr;
midPtr=&sortedArray[mid];
int myResult = compare(keyPtr, midPtr);
if (myResult == 0)
return mid; // found it.
else if (myResult == -1)
// Call ourself for the lower part of the array
return rBinarySearch(sortedArray, first, mid-1, key, compare);
else
// Call ourself for the upper part of the array
return rBinarySearch(sortedArray, mid+1, last, key, compare);
}
return -1;
}
Compare function
int compare( const void* a, const void* b )
{
int* arg1 = (int*) a;
int* arg2 = (int*) b;
if( *arg1 < *arg2 ) return -1;
else if( *arg1 == *arg2 ) return 0;
else return 1;
}
I also tried changing the compare function to a template but that didnt work either. Here is how I did that
template <typename T>
int compare (const T *a, const T *b)
{
T temp = *a - *b;
if (temp > 0)
return 1;
else if (temp < 0)
return -1;
else
return 0;
}
Here is how I am trying to call the functions:
Array<int> a1(5);
a1.SetMember(0, 3);
a1.SetMember(1, 11);
a1.SetMember(2, 9);
a1.SetMember(3, 13);
a1.SetMember(4, 7);
a1.PrintArray();
a1.SortArray();
a1.PrintArray();
int index=rBinarySearch(a1.getArray(), 1, 4, 9, compare);
The above works.
The following doesnt work
Array<char> a1(5);
a1.SetMember(0, 'k');
a1.SetMember(1, 's');
a1.SetMember(2, 't');
a1.SetMember(3, 'u');
a1.SetMember(4, 'v');
a1.PrintArray();
a1.SortArray();
a1.PrintArray();
int index=rBinarySearch(a1.getArray(), 0, 4, 't', compare);
Thanks for your help
k