(c++ is the code used) Example quiz questions Implement a function that searches
ID: 3936537 • Letter: #
Question
(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)Explanation / Answer
#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;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.