C++ Program to conduct binary search for any alphabet [a-z] out of an array
#include <ctype.h>
#include <conio.h>
#include <iostream.h>
#define max 26
char array[max] = "\0";
void initialise()
{
for(int i=0; i<max; i++)
{
array[i] = (char)(65+i);
}
}
int binsearch(int low, int high, int &num)
{
int mid = (high+low)/2;
if( array[mid] == num )
{
return mid;
}
else if( low >= high )
{
return -1;
}
else if( num > array[mid] )
{
return binsearch(mid+1, high, num);
}
else if( num < array[mid] )
{
return binsearch(low, mid-1, num);
}
else return -2;
}
void main()
{
char alpha;
int number;
int result;
clrscr();
initialise();
cout << "Enter the alphabet to search [lower case]: ";
cin >> alpha;
number = (int)toupper(alpha);
result = binsearch(0, max, number);
if( result >= 0 )
{
cout << "Found at index # : " << result+1;
}
else if( result == -1 )
{
cout << "Not Found";
}
else cout << "Unspecified Error";
getch();
}
Related Posts : C++ Programs
0 comments:
Post a Comment