Question: Hello, I am having a problem with my c + + assignment and wondering what I can do to fix it Instructions are: Write a

Hello, I am having a problem with my c++ assignment and wondering what I can do to fix it
Instructions are:
Write a version of the binary search algorithm that can be used to search a list of strings. (Use the selection sort that you designed in Exercise 8 to sort the list.) Write a program to test the function and prompt the user to enter 10 strings. The program should output the position of the string if found in the list and the following message if not:
x is not in the list
What I got so far:
#include
#include
#include
// Binary search function for integers
int binarySearch(const std::vector& arr, int key){
int left =0;
int right = arr.size()-1;
while (left <= right){
int mid = left +(right - left)/2;
if (arr[mid]== key){
return mid; // Key found, return its position
}
if (arr[mid]< key){
left = mid +1;
} else {
right = mid -1;
}
}
return -1; // Key not found
}
int main(){
std::vector intList;
int key;
// Input 10 integers from the user
for (int i =0; i <10; i++){
std::cout << "Enter integer "<<(i +1)<<": ";
std::cin >> key;
intList.push_back(key);
}
// Sort the list of integers
std::sort(intList.begin(), intList.end());
// Prompt the user to enter an integer to search for
std::cout << "Enter an integer to search for: ";
std::cin >> key;
// Perform binary search
int result = binarySearch(intList, key);
if (result !=-1){
std::cout << key <<" is found at position "<< result << std::endl;
} else {
std::cout << key <<" is not in the list." << std::endl;
}
return 0;
}
My output(the problem)
Enter integer 1: 2
Enter integer 2: 4
Enter integer 3: 5
Enter integer 4: 6
Enter integer 5: 23
Enter integer 6: 24
Enter integer 7: 28
Enter integer 8: 64
Enter integer 9: 3
Enter integer 10: 10
Enter an integer to search for: 10
10 is found at position 5
My problem is that 10 should be on position 10 but says its position 5. Its late at night so I am tired atm. Please make sure yours is runnable. ty

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!