Answer to Question #193980 in C++ for Akash

Question #193980

Explain the Binary search approach for the following elements to search 7 in the array list. 2,4,13,45,87,100 write the logical part of the program also.


1
Expert's answer
2021-05-16T12:35:20-0400

Binary search is the search technique which works efficiently on the sorted lists. Hence, in order to search an element into some list by using binary search technique, we must ensure that the list is sorted.

Binary search follows divide and conquer approach in which, the list is divided into two halves and the item is compared with the middle element of the list. If the match is found then, the location of middle element is returned otherwise, we search into either of the halves depending upon the result produced through the match.


code for given problem.

#include<iostream>
using namespace std;
int searching(int arr[], int l, int r, int x){
  if(r>=l){
    int mid=l+(r-l)/2;
    if(arr[mid]==x)
      return mid+1;
    if(arr[mid]>x)
      return searching(arr,l,mid-1,x);
    return searching(arr,mid+1,r,x);
  }
  return -1;
}
int main(void){
  int arr[]={2,4,13,45,87,100};
  int x=7;
  int n=sizeof(arr)/sizeof(arr[0]);
  int result= searching(arr,0,n-1,x);
  (result==-1) ? cout<<"given element in not present in array"
                    :cout<<"Element is present at index"<<result;
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS