Question

In: Computer Science

Part 1 1. Implement the binary search function. The function should take as formal parameters an...

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.

Solutions

Expert Solution

#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.


Related Solutions

Bisection search 1. In MATLAB, implement a function that performs a bisection search. It should take...
Bisection search 1. In MATLAB, implement a function that performs a bisection search. It should take the following parameters: • F: A function (assumed to be continuous) whose roots you want to find, • a: A floating-point number giving the left endpoint of the initial interval in which you want to search for a root of F. • b: A floating-point number giving the right endpoint of the initial interval. • delta: A non-negative floating-point number giving the acceptable proximity...
I am trying to implement a search function for a binary search tree. I am trying...
I am trying to implement a search function for a binary search tree. I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19" Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out. Here is my code: #include<iostream> using namespace std; class node {...
Implement a function to find a node in a binary search tree. Using the following class...
Implement a function to find a node in a binary search tree. Using the following class and function definition. If a node with a matching value is found, return a pointer to it. If no match is found, return nullptr. #include <iostream> class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode *find(int item) { //implement code here return nullptr; } int main() {    root = new...
Implement a function to remove a leaf node from a binary search tree. Using the following...
Implement a function to remove a leaf node from a binary search tree. Using the following class and function definition: class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode * remove_leaf(int item, bool &removed) { // implement } The remove function will return the node with the item if it's present in the tree. If the node is a leaf node and is removed by the function,...
Implement a substring search function which searches a string for a given keyword. The function should...
Implement a substring search function which searches a string for a given keyword. The function should return a pointer to the address of the first character of the substring within the original string, if it exists. If the substring is not found within the string, return NULL. If the input is found, print "Key found." otherwise print "Key not found." Your program’s input and output should match what is seen in the example run. • You may only use stdio.h....
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the...
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the template provided under the PolyLearn assignment, using the class TreeNode that is also provided. You may (should) implement helper methods that make your code easier to write, read, and understand. You will also need to write test cases of your own as you develop the methods. You may use iterative and/or recursive functions in your implementation. The following starter files are available . •...
Write a function in R named counts. This function should take as parameters a numeric vector...
Write a function in R named counts. This function should take as parameters a numeric vector x and also a number indicating a number of bins n. The function will consider the range [min(x),max(x)], and then consider a parti- tion of this interval into n non-overlapping equally sized half open intervals: I1 = [min(x),b1),I2 = [b1,b − 2),...,In = (bn−1,max(x)]. Note that since the intervals are equally sized, the value of bi is constrained. The function will then return a...
using python 1. #Write a function called multiply_file_by_index. This function #should take two parameters, both strings....
using python 1. #Write a function called multiply_file_by_index. This function #should take two parameters, both strings. The first string is #the filename of a file to which to write (output_file), and #the second string is the filename of a file from which to read #(input_file). # #In the input file, there will be an integer on every line. #To the output file, you should write the integer from the #original file multiplied by the line number on which it #appeared....
Binary Search Tree (Part 1): Note: This is the first part of a 2-part lab. Only...
Binary Search Tree (Part 1): Note: This is the first part of a 2-part lab. Only this part is due on Oct 29. But please get it working or you will struggle with the second part. For the second part, the data type will be changing. For now, it is a string. Contents Explanation: 2 BST.cpp: 2 Code you must write: 2 bool insert(string s) (7): 2 TNode *find(string s) (4): 2 void printTreeIO(Tnode *n)(3): 2 void printTreePre(Tnode *n) (3):...
Java String search Design and implement a recursive version of a binary search.  Instead of using a...
Java String search Design and implement a recursive version of a binary search.  Instead of using a loop to repeatedly check for the target value, use calls to a recursive method to check one value at a time.  If the value is not the target, refine the search space and call the method again.  The name to search for is entered by the user, as is the indexes that define the range of viable candidates can be entered by the user (that are...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT