/** * BinarySearch.cpp - Implementation and test driver for the binary search *
ID: 3543121 • Letter: #
Question
/**
* BinarySearch.cpp - Implementation and test driver for the binary search
* algorithm.
*
* TODO: Include your name and course number here.
*/
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int binarySearch(string list[], int length, string item);
int main(int argc, char **argv)
{
string stars[] = {
"Adhafera", "Al Athfar", "Al Gieba", "Aladfar", "Almeisan", "Alterf",
"Coxa", "Denebola", "Mebsuta", "Mekbuda", "Pollux", "Propus",
"Ras Elased", "Rasalas", "Sheliak", "Sulafat", "Tejat", "Tsze Tseang",
"Wasat", "Zozma"
};
int numberOfStars = 20;
string item;
int found = -1;
// Call binarySearch to find an item in the array
item = "Pollux";
found = binarySearch(stars, numberOfStars, item);
cout << item << " is at index " << found << endl;
item = "Sol";
found = binarySearch(stars, numberOfStars, item);
cout << item << " is at index " << found << endl;
item = "Sulafat";
found = binarySearch(stars, numberOfStars, item);
cout << item << " is at index " << found << endl;
cout << " ** Press any key to continue ** ";
getchar();
return 0;
}
int binarySearch(string list[], int length, string item)
{
// TODO: Implement the details of the binary search function. Be sure
// to read the textbook chapter before working on this problem. The
// funciton will return -1 if the item is not found in the array.
return -1;
}
2. (a) Modify the BinarySearch.cpp listed above to implement the required function for a binary search
algorithm. Once the function has been implemented, the program returns the index location of the item in
the array if it is found; otherwise a -1 will be returned. Remember that arrays in C++ are zero-based, so
the first position has an index of 0.
2. (b) Suppose the declaration for the stars array in Problem 2(a) was as follows:
string stars[] = {
"Sheliak", "Sulafat", "Aladfar", "Al Athfar", "Denebola", "Al Gieba",
"Zozma", "Ras Elased", "Adhafera", "Coxa", "Tsze Tseang", "Alterf",
"Rasalas", "Pollux", "Almeisan", "Wasat", "Mebsuta", "Mekbuda",
"Propus", "Tejat"
};
Briefly explain whether or not this would cause a problem for our binarySearch() function.
No award until both (a) and (b) have been answered.
Explanation / Answer
Binary search is one of my favorites.
2(A)
Here is the code for you Binary search function:
The function I gave you is recursive.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.