Modify the program so it performs a binary search instead of a linear search. He
ID: 3629200 • Letter: M
Question
Modify the program so it performs a binary search instead of a linear search.Here my code:
Comment code please! Thanks
// performs a linear search on an integer array.
#include <iostream>
using namespace std;
// Function prototype
int searchList(int [], int, int);
const int SIZE = 10;
int main()
{
int tests[SIZE] = {13579,26791,33445,55555,62483,77777,79422,85647,93121};
int results,lot;
cout<<"Enter lottery number:";
cin>>lot;
// Search the array for 100.
results = searchList(tests, SIZE,lot);
// If searchList returned -1, then 100 was not found.
if (results == -1)
cout << "Looser!! ";
else
{
// Otherwise results contains the subscript of
// the first 100 in the array.
cout << "Winner!! ";
}
system("pause");
return 0;
}
//*****************************************************************
// The searchList function performs a linear search on an *
// integer array. The array list, which has a maximum of numElems *
// elements, is searched for the number stored in value. If the *
// number is found, its array subscript is returned. Otherwise, *
// -1 is returned indicating the value was not in the array. *
//*****************************************************************
int searchList(int list[], int numElems, int value)
{
int index = 0; // Used as a subscript to search array
int position = -1; // To record position of search value
bool found = false; // Flag to indicate if the value was found
while (index < numElems && !found)
{
if (list[index] == value) // If the value is found
{
found = true; // Set the flag
position = index; // Record the value's subscript
}
index++; // Go to the next element
}
return position; // Return the position, or -1
}
Explanation / Answer
//I have just added one more method to add binary search - binarySearchList() #include using namespace std; // Function prototype int binarySearchList(int [], int, int, int); int searchList(int [], int, int); const int SIZE = 10; int main() { int tests[SIZE] = {13579,26791,33445,55555,62483,77777,79422,85647,93121}; int results,lot; coutlot; // Search the array for 100. //results = searchList(tests, SIZE,lot); results = binarySearchList(tests, lot, 0, (SIZE-1)); // If searchList returned -1, then 100 was not found. if (results == -1) coutRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.