Hello here\'s my binary search function: int binarySearch(int ar[], int valueSea
ID: 3656479 • Letter: H
Question
Hello here's my binary search function: int binarySearch(int ar[], int valueSearchedFor) { int first = 0, last = 9, position = -1, middle; bool found = false; while ((!found) && (first <= last)){ middle = (last + first) / 2; if (ar[middle] == valueSearchedFor){ position = middle; found = true;} else if (ar[middle] < valueSearchedFor) { first = middle + 1;} else { last = middle + 1;} } return position; } Here's what I'm running through it: int values[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; cout << "------ Section 1 ------ "; // testing Binary Search result = binarySearch(values, 100); if (result != 9) { cout << "Section 1: Test Case 3 of 3 - fail "; } else { cout << "Section 1: Test Case 3 of 3 - pass "; } When I run this test ^ it always fails, and cant find the value 100...could someone show me whyExplanation / Answer
#include<iostream>
#include<conio.h>
using namespace std;
int binarySearch(int ar[], int valueSearchedFor)
{cout< int first = 0, last = 9, position = -1, middle;
bool found = false;
while ((!found) && (first <= last))
{ middle = (last + first) / 2;
if (ar[middle] == valueSearchedFor)
{ position = middle; found = true;}
else if (ar[middle] < valueSearchedFor)
{ first = middle + 1;}
else { last = middle - 1;}
}
return position; }
int main()
{
int values[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
cout << "------ Section 1 ------ ";
// testing Binary Search
int result = binarySearch(values, 65);
if (result==-1) ----------------------------------------------------------------------only this line was wrong
{ cout << "Section 1: Test Case 3 of 3 - fail "; }
else { cout << "Section 1: Test Case 3 of 3 - pass "; }
getch();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.