Searching algorithm

my program generates an array of random numbers.
I want to then search a specific number within the array.
If the number is in the array then a message apopears on the console saying that its there.
I'm using the binary search algorithm to do this.
However im having no luck, can you see whats wrong with my code??

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <cstring>

using namespace std;

int size;
int getSize() { return size; }
int input;
int x, i, n;
int searchNumber;
int* numArray;

void generateArray()
{
cout << "Please enter the amount of random numbers to be generated: ";
cin >> input;

srand(time(NULL));

numArray = new int[input];

size = input;

cout << "Unsorted" << endl;

for(x = 1; x <= input; x++)
{
numArray[x] = 1+(rand()%10000);
cout << numArray[x] << " ";
}
}

void selectionSort(int numArray[])
{
int small=0,pos=0,tmp=0;

for(i=0;i<=size-1;i++)
{
tmp = numArray[i];
small = tmp;
pos = i;

for(int j=i;j<=size;j++)
{
if(numArray[j]<tmp)
{
tmp=numArray[j];
pos=j;
}
}

numArray[i] = tmp;
numArray[pos] = small;
}
for(i=1;i<=size;i++)
{
cout << numArray[i] << " ";
}
return;
}

int binarySearch(int numArray[], int size, int searchValue)
{
int low = 0;
int high = size - 1;

int mid;

while (low <= high)
{
mid = (low + high) / 2;

if(searchValue == numArray[mid])
{
return mid;
}
else if (searchValue > numArray[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}

return -1;

}

int main()
{
int userValue;

generateArray();

cout << endl;

cout << "Sorted" << endl;

selectionSort(numArray);

cout << endl;

cout << "Please search for a value within the array: ";
cin >> userValue;

int result;

binarySearch(numArray, size, userValue);

if(userValue == numArray[i])
{
cout << "The number " << userValue << " was found in the array" << endl;
}
else
{
cout << "The number " << userValue << " was not found. " << endl;
}
cin.ignore(2);
}
Limit the scope of your variables.
You never use the returned value of `binarySearch()'
1) In C, indices for an array of size N go from 0 to N-1. All your loops looking like for( i=1; i <= N; i++ ) need to be changed to for( i=0; i < N; i++ ).
2) You declare "result" but forget to assign it with the return value of binarySearch().
3) You should compare "userValue" with numArray[result], not numArray[i].
Topic archived. No new replies allowed.