# Write a program to search an element in the array.Plz implement this using binary search.Comments must be added .Do it in c++

Question
1 views

Write a program to search an element in the array.

Plz implement this using binary search.

Do it in c++

check_circle

Step 1

Program Approach –

• Include the essential header files.
• Define the main function.
• Define the variables as per the requirement.
• Define the array and initialize the values in it.
• Define a recursive binary search function.
• Call the recursive binary search function.
• Display the output.

Binary Search approach -

• Equate the number to be searched with the middle element of the array.
• If the number matches with middle element of the array, then return the index number of the middle element.
• If the number is greater than the middle element, then the number can only exist in the right half subarray after the middle element. Repeat this process for the right subarray.
• Else the number is smaller than the middle element then the number can only exist in the left half subarray before the middle element. Repeat this process for the left sub-array.
Step 2

Code (in C++) -

#include <iostream>
using namespace std;
//defining the recursive binary search function
int bS(int a[], int len, int r, int num)

if (r >= len) {
int mid = len + (r - len) / 2;
//when the number is found at the middle
if (a[mid] == num)
return mid;
//when the number is smaller than the middle element of the array,then it must be in the left sub array
if (a[mid] > num)
return bS(a, len, mid - 1, num);
//else the element must be in the right sub array
return bS(a, mid...

### Want to see the full answer?

See Solution

#### Want to see this answer and more?

Solutions are written by subject experts who are available 24/7. Questions are typically answered within 1 hour.*

See Solution
*Response times may vary by subject and question.
Tagged in 