0

C++ what is position doing in this binary search function?

int binarySearch(int array[], int size, int value) //value is the number you want to look for { int first = 0, // First array element last = size - 1, // Last array element middle, // Mid point of search position = -1; // Position of search value bool found = false; // Flag int numOfRounds = 0; while (!found && first <= last) { middle = (first + last) / 2; // Calculate mid point if (array[middle] == value) // If value is found at mid { found = true; position = middle; cout << "value is found at mid" << endl; cout << "it is found!" << endl; } else if (array[middle] > value) // If value is in lower half { last = middle - 1; cout << "value is found at lower half" << endl; numOfRounds++; } else { first = middle + 1; // If value is in upper half cout << "value is found at upper half" << endl; numOfRounds++; } if (!(array[middle] == value)) { cout << "value is NOT found" << endl; } cout << "Number of rounds: " << numOfRounds << endl; cout << "- - - - - - - - - - - - - - - - -" << endl; } return position; }

21st Jul 2017, 7:08 PM
PurePureMilk
3 ответов
+ 4
<position> is used to store the index of array element that contains the value you were looking for. In case the search failed, the value of <position> will not be changed from its initial value which is -1. The function use <position> as its return value.
21st Jul 2017, 8:48 PM
Ipang
+ 1
Well, position is initialized as -1 and the only place where it gets a value is when array[middle] == value, there it gets the value of middle. So position returns the position(index) where the value is found, and -1 if not. Kinda useless if you ask me cause you can just return middle immediatly when it is found but everyone their own thing I guess. ^^
21st Jul 2017, 8:38 PM
Dennis
Dennis - avatar
+ 1
You may want to simplify your code: int last = size - 1; if (size < 1) return -1; // Error code mid = last / 2; while (last > -1) { if (array[last] == value) break; last--; } switch (last) { case -1: std::cout << "Not found!"; break; case mid: std::cout << "Found at middle"; break; default: std::cout << "Found at " << last; break; } If you have any questions, don't be shy :)
22nd Jul 2017, 12:31 AM
Jamie
Jamie - avatar