Computer Science Canada

What am I doing wrong????

Author:  bobbySmith [ Tue Mar 24, 2009 1:53 pm ]
Post subject:  What am I doing wrong????

Confused I'm going nut's!!!

c++:
#include<iostream>
#include<string>

using namespace std;

bool BinarySearch(int info[], int, int, int, int& istep);

int main()
{
        int istep;
        int info[10] = {2, 6, 9, 14, 23, 65, 92, 96, 99, 100};
        int fromLocation, toLocation, item;
        string cmd;
        do{
                cout << "Insert item, from location and to location" << endl;
                cin >> item;
                cin >> fromLocation;
                cin >> toLocation;
                if(fromLocation < 0 || fromLocation > 9 || toLocation > 9 || toLocation < 0)
                continue;
                BinarySearch(info, item, fromLocation, toLocation, istep);
                cout << "Would you like to exit? type 'exit' to exit or type 'yes' to go again" << endl;
                cin >> cmd;
        }while(cmd != "exit");
       
}

bool BinarySearch(int info[]int item, int fromLoc, int toLoc, int &istep) {
   istep = 0;
   if (fromLoc > toLoc)
           return false;
   int midValue = (toLoc - fromLoc)/2;
   if (item == info[midValue])
   {
           ++istep;
           cout << "Yes, value found at step " << istep << endl;
           return true;
   } else if (item < info[midValue])
   {
           return BinarySearch(info, item, fromLoc, midValue - 1, ++istep);
   } else if(item > info[midValue])
   {
           return BinarySearch(info, item, midValue + 1, toLoc, ++istep);
   }
}


Mod Edit: Remember to use syntax tags! Thanks Smile
code:
[syntax="cpp"]Code Here[/syntax]

Author:  DemonWasp [ Tue Mar 24, 2009 2:06 pm ]
Post subject:  RE:What am I doing wrong????

First, please use either [ code ] or [ syntax ] tags to properly align / highlight your code. This makes it a lot easier for us to help you.

Second, when describing a problem, "it doesn't work" is insufficient. Tell us what your output is and what your expected output is, and what you've already tried.

I'm not going to try solving this problem at the moment; instead, I'll point you in the right direction. Try putting an output line right as you enter BinarySearch that goes something like this:

code:
cout << "BinarySearch ( item="<<item<<", from="<<fromLoc<<", to="<<toLoc<<", step="<<istep<<")"<<endl;


Then see what output that produces compared to what you would expect it to produce.

Author:  bobbySmith [ Tue Mar 24, 2009 2:25 pm ]
Post subject:  RE:What am I doing wrong????

Ah ha! Thanks DemonWasp. I see it is working but istep won't add up the amount of steps it takes. It stays at 1.

Author:  bobbySmith [ Tue Mar 24, 2009 2:28 pm ]
Post subject:  RE:What am I doing wrong????

Never mind, I got it. Stupid mistake. Thanks for the help though.


: