Hello
Let me say this, the site has been very helpful especially when a person is willing to try the code themselves instead of just asking for answers. I feel that it helps one learn much quicker with me being new to C++...with that being said, the below code is giving me some erroneous answer during the execution.
The user enters a number from the Array list or a number that is not on the array list and the program is supposed to tell whether the number exist in the array and where it is located at what index.
The strange thing is that if you notice the 4th index, which contains the number 3302, if you run the program and enter the search value of 3302, the program gives out the appropriate answer...
...says 3302 found at index=4.
If you run the program and enter a number which isn't in the list, it says "not found", which is also CORRECT.
However, the issue arises when you enter any other number into the search value say, 1681 or 7140, both of which are in the array list but the program skips over them as if they are not there and says "Not Found".
I have run the debugger and from what I have investigated, somehow, my function definition is not giving me the correct answer. It is saying that my "if(first <= last)" condition is not true and returning a -1; however it also does that when I enter 3302 yet returns accurately as it is supposed to.
Can anyone enlighten me on what is going on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include<iostream>
using namespace std;
//declare function
int binSearch (int A[], int size, int tarVal);
void main()
{
const int Array_Size=10;
int myArray[Array_Size]={1681, 2106, 2309, 3184, 3302, 4190, 4498, 6512, 7140, 9963};
cout << "The "<< Array_Size << " array elements are: " << endl;
for (int i=0; i<Array_Size; i++)
{
cout << myArray[i] << " ";
}
cout << endl << "Enter the target value: ";
int tarVal;
cin >> tarVal;
int index = binSearch(myArray, Array_Size, tarVal);
if (index > 0)
{
cout << "Target value= " << tarVal << " found at array index " << index << endl;
}
else
cout << "Target Value = " << tarVal << " not found " << endl;
}
int binSearch (int A[], int size, int tarVal)
{
int first=0, last=size-1, mid;
if(first <= last)
{
mid = (first + last)/2;
}
if (tarVal < A[mid])
{
last = mid-1;
}
else if (tarVal > A[mid])
{
first = mid+1;
}
else return mid;
{
return -1;
}
}
|