In: Computer Science
Part 1
1. Implement the binary search function. The function should take as formal parameters an array of integers, its size and target, and returns
(a) in the case of successful search – the position (index) of the target in the array
(b) in the case of unsuccessful search – an exception with the message “Unsuccessful search” thrown from the function to the user.
2. The binary search works correctly only when the input is sorted. This requirement should be satisfied before the algorithm starts the search operation. Therefore if the input is unsorted the exception with the message “Unsorted input” should be thrown by the function.
3. Test the binary search function using different inputs in the main function.
(a) Use const int SIZE to define the number of input elements.
(b) The main function should provide the try and catch mechanism.
#include <iostream> using namespace std; const int SIZE = 10; bool isArraySorted(int data[], int size) { for(int i=0; i<size-1; i++) { if(data[i] > data[i+1]) { return false; } } return true; } int binarySearch(int data[], int size, int searchItem) { if(!isArraySorted(data, size)) { throw "Unsorted input"; } int z = 0; int p = size-1; while (z <= p) { int m = z + (p-z)/2; if (data[m] == searchItem) return m; if (data[m] < searchItem) z = m + 1; else p = m - 1; } throw "Unsuccessful search"; } int main() { int values1[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int values2[SIZE] = {1, 2, 3, 4, 15, 16, 7, 8, 9, 10}; try { int index = binarySearch(values1, SIZE, 8); cout << "8 found on index " << index << " in values1 array" << endl; } catch (const char* msg) { cout << "exception with value1 array: " << msg << endl; } try { int index = binarySearch(values2, SIZE, 8); cout << "8 found on index " << index << " in values2 array" << endl; } catch (const char* msg) { cout << "exception with value2 array: " << msg << endl; } }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.