In: Computer Science
Correct this Binary Search (C++)
// This program demostrates linear search algorithm
#include <iostream>
using namespace std;
// Binary search algorith
// f is the first , l is the last , t is the target
int binarySearch(int stgrade[], int f, int l, int t)
{
while (f <= l)
{
int m = f + (l - l) / 2;
// Check if x is present at mid
if (stgrade[m] == t)
return m;
// If x greater, ignore left half
if (stgrade[m] < t)
f = m + 1;
// If x is smaller, ignore right half
else
l = m - 1;
}
// if we reach here, then element was not present
return -1;
}
int main(void)
{
int target;
int stgrade[] = { 100, 73, 94, 100, 70, 86, 55, 90, 74 };
// size of the array
int s = sizeof(stgrade) / sizeof(stgrade[0]);
cout << "This is your list" << endl;
for (int i = 0; i < s; i++)
cout << stgrade[i] << " ";
cout << endl;
cout << "Input the target to find , in or out side of your
list" << endl;
cin >> target;
// 0 is the index of 1st element
// s is the size and s-1 is in dext of last element
// target is what you want to find
int result = binarySearch(stgrade, 0, s - 1 , target);
if (result == -1)
cout << "Your target NOT FOUND in the list" <<
endl;
else
cout << "Your target is in the list " << result + 1
<< endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int binarySearch(int stgrade[], int f, int l, int t)
{
while (f <= l)
{
int m = f + (l - l) / 2;
// Check if x is present at mid
if (stgrade[m] == t)
return m;
// If x greater, ignore left half
if (stgrade[m] < t)
return binarySearch(stgrade, m + 1, l, t);
// If x is smaller, ignore right half
else
return binarySearch(stgrade, f, m - 1, t);
}
// if we reach here, then element was not present
return -1;
}
int main(void)
{
int target;
int stgrade[] = { 100, 73, 94, 100, 70, 86, 55, 90, 74 };
// size of the array
int s = sizeof(stgrade) / sizeof(stgrade[0]);
cout << "This is your list" << endl;
for (int i = 0; i < s; i++)
cout << stgrade[i] << " ";
cout << endl;
cout << "Input the target to find , in or out side of your
list" << endl;
cin >> target;
// 0 is the index of 1st element
// s is the size and s-1 is in dext of last element
// target is what you want to find
int result = binarySearch(stgrade, 0, s - 1 , target);
if (result == -1)
cout << "Your target NOT FOUND in the list" <<
endl;
else
cout << "Your target is in the list " << result + 1
<< endl;
system("pause");
return 0;
}