Reputation: 1
trying to learn some basic data structures and algorithms and ive tried to code a basic binary search but it doesn't work unless the input is the same as the middle? can anyone help?
void Search(int input) {
int array[10] = { 0.1,2,3,4,5,6,7,8,9,10 };
int first = array[0];
int last = sizeof(array) / sizeof(array[0]);;
int middle = first + last / 2;
if (input == middle) {
cout << "search succesful";
}
else if (input > middle) {
middle + 1;
Search(input);
}
else if (input < middle) {
middle - 1;
Search(input);
}
}
int main()
{
int input;
cin >> input;
Search(input);
}
Upvotes: 0
Views: 200
Reputation: 63
If you want to use recursion than you should also pass the right and left border of array and change them in your if statements. When you do middle-1
you don't change anything.
Here is binary search implemantation
int binarySearch(int nums[], int low, int high, int target)
{
// Base condition (search space is exhausted)
if (low > high) {
return -1;
}
// find the mid-value in the search space and
// compares it with the target
int mid = (low + high)/2; // overflow can happen
// int mid = low + (high - low)/2;
// Base condition (target value is found)
if (target == nums[mid]) {
return mid;
}
// discard all elements in the right search space,
// including the middle element
else if (target < nums[mid]) {
return binarySearch(nums, low, mid - 1, target);
}
// discard all elements in the left search space,
// including the middle element
else {
return binarySearch(nums, mid + 1, high, target);
}
}
Upvotes: 5