-2

Given a sorted array A, which stores n integers, and a value key. Design an efficient divide and conquer algorithm that returns the index of the value key if it can be found in array A.Otherwise, the algorithm returns 0.

kybookie
  • 11
  • 5
  • What have you tried? This is clearly a homework question. You should post at least your reasoning. – Fede Oct 11 '16 at 15:33

1 Answers1

1

I think for your description that the best choice is binary search (dichotomous search). The algorithm is to go by dividing the array in half and buying if the element found in the middle is higher, lower or equal to the item you are looking for. This is done in order to reduce search space to find the element logarithmically or determine that the element is not in the vector.The array must be ordered.

this is an example in C++

#include <vector>



bool busqueda_dicotomica(const vector<int> &v, int principio, int fin, int &x){
     bool res;
     if(principio <= fin){
         int m = ((fin - principio)/2) + principio;
         if(x < v[m]) res = busqueda_dicotomica(v, principio, m-1, x);
         else if(x > v[m]) res = busqueda_dicotomica(v, m+1, fin, x);
         else res = true;
     }else res = false;
     return res;
 }

I think your algorithm should not return 0 if not found because if you want to return the index of the element, 0 is the index of the first element

In this article is the detailed explanation of the binary search or in this other

Hector Davila
  • 180
  • 2
  • 10