0

When I run this program and enter a value to search for the program crashes(exe has stopped working, close program). Once when entering value 65, I got an infinite loop of Number not found Enter a value to search (-1 to quit):

Here is the code:

#include <iostream>
using namespace std;

void Search(int[], int * , int * );

int main()
{

  int i,KEY,num, array[] = {98,87,76,65,54};


  for(i=0;i<5;i++)
    cout << array[i] << " ";

  Search(array, &KEY, &num);

  cout << endl;
  system("pause");
  return 0;
}

void Search(int arr[5], int * current, int * numel)
{

  int low, high,search,N;

  cout << "\nWhat Number would you like to search for? (-1 to quit) : ";
  cin >> search;

  while(search!=-1)
  {
    low=0;
    high=N-1;
    while(low<=high)
    {
      *current=(low+high)/2;
      if (search > arr[*current])
        low=*current+1;
      else if(search<arr[*current])
        high=*current-1;
      else
        break;
    }
    if(arr[*current]==search)
      cout << "Number found at index " << *current << endl;
    else
      cout << "Number not found." << endl;
    cout << "Enter a value to search (-1 to quit) :";
  }
  return;
}
8
  • MY question is why is my code failing/crashing? Commented Oct 31, 2012 at 1:09
  • I suggest doing some research into the crash on your own. Start by using a debugger or inserting output statements to find where the crash occurs. Then work backwards from there to try to find where the problem could be. Commented Oct 31, 2012 at 1:12
  • thanks, seems that the array values aren't being passed to the function and/or if a value is not found the loop never ends. Commented Oct 31, 2012 at 1:29
  • 1
    ah!! the array wasn't in low to high order. Commented Oct 31, 2012 at 1:50
  • 1
    thanks for the guidance, program is running well. Commented Oct 31, 2012 at 2:10

2 Answers 2

1

For starters, there's no way out of the main loop in Search if the number sought is not in the array.

Then you're using high before it's been given any value.

There may be other problems. How did you test this while you were developing it?

Sign up to request clarification or add additional context in comments.

Comments

0

N isn't initialized, so who knows what this statement:

high=N-1;

will do?

3 Comments

changed int low, high,search,N; to int low, high,search,N=5;
And did that change anything? The code probably has some other problems. Stepping through with a debugger or throwing in some printf() statements (if you don't want to use a debugger for some reason) might provide some insight.
that stopped the crashing but now I have infinite loops for every search.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.