c is the code used Example quiz questions Implement a functi

(c++ is the code used)
Example quiz questions Implement a function that searches for a given value k in an array of integers. Do not assume the values are in order. If the value is found, the function returns the index of the value in the array; otherwise it returns -1. The following is a declaration of the function. int search(int a[], int size, int k) Write a function called binarySearch that finds an occurrence of an integer k in an array a using binary search where the integers in a form an increasing sequence. The function signature is given below. The function returns true if k is in a, otherwise it returns false. Do not use the search function available in the C++ standard library. bool binarySearch(int a[], int size, int k)

Solution

#include<stdio.h>

int search(int a[], int size, int k){
   int i=0;
   for(i=0;i<size;i++){
       if(a[i]==k){
           return i;
       }
   }
   return -1;
}

bool binarysearch(int a[], int size, int k){
   int start=0,end=size,mid;
   while(start < end){
       mid = (start+end)/2;
       if(a[mid]<k){
           start = mid+1;
       }
       else if(a[mid]>k){
           end = mid;
       }
       else{
           return true;
       }
   }
   if(a[mid]==k){
       return true;
   }
   return false;
}

(c++ is the code used) Example quiz questions Implement a function that searches for a given value k in an array of integers. Do not assume the values are in or

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site