-
Help! with binary search
Code:
#include<iostream>#include<cstdlib>
#include<ctime>
void selectionSort(int[], int);
int binarySearch(const int[], int, int);
int main() {
const int SIZE = 10;
const int MAX = 100;
int Array[SIZE] = { 0 };
time_t t;
srand((unsigned)time(&t));
int search, results;
for (int i = 0; i < SIZE; i++)
{
Array[i] = (rand() % MAX) + 1;
}
std::cout << std::endl;
std::cout << "Array is " << std::endl;
for (int i = 0; i < SIZE; i++)
{
std::cout << Array[i];
}
std::cout << "Sorted Array is " << std::endl;
selectionSort(Array, SIZE);
{
for (int j = 0; j < SIZE; j++)
std::cout << Array[j] << std::endl;
}
std::cout << "What is your number " << std::endl;
std::cin >> search;
results = binarySearch(Array, SIZE, search);
if (results == -1)
std::cout << "No" << std::endl;
else
{
std::cout << "Yes" << std::endl;
}
system("PAUSE");
return 0;
}
void selectionSort(int array[], int size)
{
int temp, i, j;
for (i = 0; i < size; i++)
{
j = i;
while (j > 0 && (array[j - 1] > array[j]))
{
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
j--;
}
}
}
int binarySearch(const int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last - middle - 1;
else first = middle + 1;
}
return position;
}
When I run this code I get my selection sort but I don't get the return of my binary search
-
Maybe you forgot an assignment?
Code:
$ g++ -Wall -Wextra foo.cpp
foo.cpp: In function ‘int binarySearch(const int*, int, int)’:
foo.cpp:97:27: warning: statement has no effect [-Wunused-value]
last - middle - 1;
^
-
Are you saying I need a pointer to my function?
-
How did you come up with that?
Read the error message.
"no effect" means you may as well have written
Code:
else if (array[middle] > value)
; // do nothing
else first = middle + 1;
Let me spell it out.
Write
last = middle - 1;