Question

Write a C++ function binsearch that carries out the binary search algorithm on a sorted array...

Write a C++ function binsearch that carries out the binary search algorithm on a sorted array of integers. Your function takes as parameters an array of integers (sorted in increasing order), the size of the array, and a target integer to search for. The function returns the index of the target in the array, and returns -1 if the target is not in the array.

The file main1.txt on the webpage contains code that generates a specific array of integers in increasing order. (Do not change the code that generates the array.) Add your binsearch function to this C++ program. Use your function to search for the elements {39, 47, 208, 288, 427, 685, 676, 972}.

Your program should print out each of these elements, and the return value of the function for that element, that is, the index in the array a where the element was found, or the integer -1 if the element was not found.

#main1.txt

#include <iostream>
# include <cstdlib>

using namespace std;

int main()
{
    int a[100];
    srand(300);
    for ( int k = 0; k < 100; ++k){
        a[k] = 10*k + rand()%10;
    }

}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

The following code of the program is explained with comments.

I have included the print_array function to print the array contents to visually check whether the element searched using bin_search exists in the array or not.

Please let me know if you have any doubts regarding the code.

Code:

#include <iostream>
#include <cstdlib>
using namespace std;

// This function searches a element in a array using binary search
int binsearch(int a[],int size,int target_int)
{
    // This variable keeps track of indexes of left half array
    int left_half_index = 0;
    // This variable keeps track of indexes of right half array
    int right_half_index = size - 1;
    // Until left_half_index is less than or equal to right_half_index, this loop is iterated
    while(left_half_index <= right_half_index)
    {

        // Calculating the mid index of the array
        int mid_index = (left_half_index + right_half_index) / 2;

        // If the value at index mid_index in array is less than target_int
        if(a[mid_index] < target_int)
        {
            // Update the value of left_half_index
            left_half_index = mid_index + 1;
        }

        // Else If the value at index mid_index in array is greater than target_int
        else if(a[mid_index] > target_int)
        {
            // Update the value of right_half_index
            right_half_index = mid_index - 1;
        }

        // Else the target_int is found
        else
        {
            // So return the mid_index
            return mid_index;
        }
    }
    // If this step is reached, it means that the target_int is not in the array. So return -1
    return -1;
}

// This function prints the array
void print_array(int a[], int size)
{
    cout<<"Array contents:\n";

    for(int i = 0;i<size;i++)
    {
        // If 10 elements are printed, print a new line
        if((i+1)%10 == 0)
        {
            cout<<endl;
        }

        // Else print the element
        else
        {
            cout<<a[i]<<" ";
        }
    }
    // Print a newline
    cout<<endl;
}

// This is the main function
int main()
{
    // Creating an array of type int and of size 100
    int a[100];
    // Setting the seed of random function
    srand(300);

    // Generating 100 random values and inserting them into the array
    for ( int k = 0; k < 100; ++k)
    {
        a[k] = 10*k + rand()%10;
    }

    // This is an array of elements whose every element is to be searched in the array a
    int values_searched[] =  {39, 47, 208, 288, 427, 685, 676, 972};
    // Calculating size of the array a
    int a_size = sizeof(a) / sizeof(a[0]);

    // Printing the array
    print_array(a,a_size);

    // Calculating size of the array values_size
    int values_size = sizeof(values_searched) / sizeof(values_searched[0]);
    // Iterating over values_searched array
    for(int k=0;k<values_size;k++)
    {
        // Searching if the element exists in the array a
        int result = binsearch(a,a_size,values_searched[k]);
        // If the element exists
        if(result != -1)
        {
            // Print the element and it's index
            cout<<"Value "<<values_searched[k]<<" is present in the array at index "<<result<<endl;
        }
        // Else
        else
        {
            // Print that element doesn't exist in the array
            cout<<"Value "<<values_searched[k]<<" is not present in the array"<<endl;
        }
    }
}

Sample Output:

Add a comment
Know the answer?
Add Answer to:
Write a C++ function binsearch that carries out the binary search algorithm on a sorted array...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In C++: Write a C++ function binsearch that carries out the binary search algorithm on a...

    In C++: Write a C++ function binsearch that carries out the binary search algorithm on a sorted array of integers. Your function takes as parameters an array of integers (sorted in increasing order), the size of the array, and a target integer to search for. The function returns the index of the target in the array, and returns -1 if the target is not in the array. Using the code below, add your binsearch function to this C++ program. (Do...

  • 1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array...

    1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array of distinct integers, and an integer x, return the index of x in the array. If the element x is not present in the array, return -1. "Almost sorted" means the following. Assume you had a sorted array A[0…N], and then split it into two pieces A[0…M] and A[M+1…N], and move the second piece upfront to get the following: A[M+1]…A[N]A[0]…A[M]. Thus, the "almost sorted"...

  • Just Q3 and Q4 Q1] Write a C function to implement the binary search algorithm over...

    Just Q3 and Q4 Q1] Write a C function to implement the binary search algorithm over an array of integer numbers and size n. The function should return the index of the search key if the search key exists and return - 1 if the search key doesn't exist. [10 Points] Q2] Write a C function to implement the selection sort algorithm, to sort an array of float values and size n. The function should sort the array in ascending...

  • Given a sorted (in ascending order) integer array nums of n elements and a target value,...

    Given a sorted (in ascending order) integer array nums of n elements and a target value, write a method to perform a binary search for a target value in nums. If target exists, then return its index, otherwise return -1. Analyze the running time, T(n). public int search(int[] nums, int target) { // YOUR CODE GOES HERE } // end search

  • Write and test a function in C++ that uses the binary search algorithm to search an...

    Write and test a function in C++ that uses the binary search algorithm to search an array of sorted strings – use a do..while loop to allow user to perform multiple searches w/o terminating the program – see sample output below. Use this name array: string names[SIZE] = { "Collins, Bill", "Smith, Bart", "Allen, Jim",         "Griffin, Jim", "Stamey, Marty", "Rose, Geri", "Taylor, Terri",         "Johnson, Jill", "Allison, Jeff", "Looney, Joe", "Wolfe, Bill",         "James, Jean", "Weaver, Jim", "Pore, Bob",...

  • In C language Write a program that includes a function search() that finds the index of...

    In C language Write a program that includes a function search() that finds the index of the first element of an input array that contains the value specified. n is the size of the array. If no element of the array contains the value, then the function should return -1. The program takes an int array, the number of elements in the array, and the value that it searches for. The main function takes input, calls the search()function, and displays...

  • In C language Write a program that includes a function search() that finds the index of...

    In C language Write a program that includes a function search() that finds the index of the first element of an input array that contains the value specified. n is the size of the array. If no element of the array contains the value, then the function should return -1. The program takes an int array, the number of elements in the array, and the value that it searches for. The main function takes input, calls the search()function, and displays...

  • In C++, make the following binary search function work on an array of strings to give...

    In C++, make the following binary search function work on an array of strings to give you the index location of the string you want in the array. It currently works on integers only. int binarySearch(int arr[], int firstIndex, int lastIndex, int target){ int index; if (firstIndex>lastIndex) index = -1; else { int mid = firstIndex + (lastIndex - firstIndex) / 2; if (target == arr[mid]) index = mid; else if (target < arr[mid]) index = binarySearch(arr, firstIndex, mid -...

  • Write a C++ function, smallestIndex, that takes as parameters an int array and its size and...

    Write a C++ function, smallestIndex, that takes as parameters an int array and its size and returns the index of the first occurrence of the smallest element in the array. To test your function, write a main that prompts a user for a list of 15 integers and outputs the index and value of the first occurrence of the smallest value. The program should print out Enter 15 integers: The position of the first occurrence of the smallest element in...

  • PLEASE IMPLEMENT YOUR SOLUTION RECURSIVELY IN C++. IT WOULD BE GREAT IF YOU COULD ALSO PROVIDE...

    PLEASE IMPLEMENT YOUR SOLUTION RECURSIVELY IN C++. IT WOULD BE GREAT IF YOU COULD ALSO PROVIDE TEST CODE FOR IT. 5) Design a recursive function to find the immediate successor of a target integer in an array o:f sorted integers. Here the immediate successor of a target is defined as the smallest number that is no smaller than the target in this sorted array int binarySuccessor(const int anArrayl, const int first, const int last, int target); In the above function...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT