) write a binary search function (using recursion) int binary search(int val, int * a, int first, int last); which searches the values in the sorted array a[] from a[first] to a[last] to find an array element with value val. if it finds val, it returns the position of val in a[]. otherwise it returns -1. for example, given the array a[]

Respuesta :

belali

#include <iostream>

#include <algorithm>

int binarySearch(int val, int *a, int first, int last) {

   if (first>last) return -1;

   int mid = first+(last-first)/2;

   if (a[mid]==val) return mid;

   // recursive

   if (val<a[mid]) return binarySearch(val,a,first,mid-1);

   else return binarySearch(val,a,mid+1,last);

}

int main(int argc, char* argv[]) {

   

   int n; std::cin>>n;

   int array[n];

   for(int i=0;i<n;i++) {

       std::cin>>array[i];

   }

   

   //Which value?

   int v; std::cin>>v;

   

   //Sort before sending the function.

   std::sort(array, array+n);

   std::cout << "Position: " << binarySearch(v,array,0,n) << std::endl;;

   return 0;

}

Ver imagen belali