linear/binary search functions not displaying anything?

377 views Asked by At

I am comparing linear and binary searching and the speed at which each does so. But when I compile the program nothing displays and I cannot figure out why. This worked when I only had the linear search part of it input and tested it. Any help would be greatly appreciated~~. Thank you.

#include <iostream>
using namespace std;

int linearSearch(const int integerArray[],int,int);
int binarySearch(const int integerArray[],int,int);
const int SIZE = 20;

    int main()
    {
        int integerArray[SIZE]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10};
        int position1,position2;

        cout << "This program will compare search efficiency for the linear and binary searches " << endl;

        position1 = linearSearch(integerArray,SIZE,7);
        position2 = binarySearch(integerArray,SIZE,7);

        cout << position1 << endl;
        cout << position2 << endl;

        return 0;
    }

    int linearSearch(const int integerArray[],int SIZE,int value)
    {
        int index = 0;
        int position1 = -1;
        bool foundNum = false;

        while(index < SIZE)
        {
            if(integerArray[index] == value)
            {
                foundNum = true;
                position1 = index;
            }
            index++;
        }
        return position1;
    }

    int binarySearch(const int integerArray[],int size,int value)
    {
        int first = 0;
        int last = size-1;
        int midpoint = (first+last)/2;
        int position2 = -1;
        bool foundNum = false;

        while(!foundNum && first<=last)
        {
            if(integerArray[midpoint] == value)
            {
                foundNum = true;
                position2++;
                return position2;
            }
            else if(integerArray[midpoint] > value)
            {
                last = midpoint-1;
                position2++;
            }
            else
                last = midpoint+1;
                position2++;


        }
        return position2;
    }
2

There are 2 answers

0
yizzlez On

In your binarySearch function midpoint is never changed, so the result is an infinite loop unless the number is found instantly.

You should update midpoint by placing midpoint = (first+last)/2; inside the loop.

0
Matt On

This sounds like a homework problem so I won't do it for you, but it seems the problem is with your binary search. Consider these items:

  1. The re-calculation of the midpoint needs to be done every iteration. You only do it once.
  2. There needs to a be a case in which you modify first, and a separate case in which you modify last. You have two cases that modify last.
  3. Do you even need a position2? Doesn't the midpoint variable serve this purpose?

Good luck!