Reputation: 125
I'am having some trouble with this program and I can not figure what I'am doing wrong; the program is supposed to be a recursive search program, however some of the functions are not being called correctly (or at all). The problem seems to center around the "bin_search" portion, and again an error pops up on the "int data [size]" portion, saying "Variable-sized object may not be initialized". Any help would be greatly appreciated. Thanks in advance!
# include <iostream> // Allows program to perform input and output
using std::cout; // program uses cout
using std::cin; // program uses cin
int bin_search ( int data[], int left, int right, int key, int NOT_FOUND)
{
// calculate the index to search
int index = ( ( ( key - data[ left ]) / ( data[ right ] - data[ left] ) )* (right - left) ) + left;
// terminating condition
if ( data[index] == key )
return key;
// terminating condition
if ( left >= right )
return NOT_FOUND;
// search recursively
if ( key < data[index] )
return bin_search ( data, left, index-1, key );
else
return bin_search ( data, index + 1, right, key );
}
// end function bin search
int main()
{
// function main begins program execution
int size = 10;
int bin;
int data[size] = {0, 7, 12, 23, 44, 335, 426, 477, 658, 921};
int key = 23;
// let the user know about the program
cout << "\n\n A program to search an element recursively.";
// search and print the results to the user
if ( bin_search( data, 0, size-1, key ) == key )
cout << "\n\n\tThe key was found.";
else
cout << "\n\n\tThe key was not found.";
// let the screen wait to see the output
cout << "\n\n\t";
system( "pause" );
return 0; // indicate program executed successfully
// end of function, main
}
Upvotes: 1
Views: 463
Reputation: 153840
A few notes:
n
elements, you want to have n + 1
positions! This way you can easily deal with an empty sequence and there is an obvious result to return if something isn't found.index
to check is far to complicated. All you want is to find the middle position of the sequence to search. The key
is certainly not part of this computation.Upvotes: 2