int =BinarySearch(char chars[], int size, char key){ //return -1 if key not foun
ID: 3602344 • Letter: I
Question
int =BinarySearch(char chars[], int size, char key){
//return -1 if key not found
}
int main(){
char letters[] = { 'b', 'd', 'g', 'm', 'n', 'q', 'x', 'z'};
const size_t= 8;
int keyIndex1 = BinarySearch(letters, SIZE, 'b');
int keyIndex2 = BinarySearch(letters, SIZE, 'c');
int keyIndex3 = BinarySearch(letters, SIZE, 'n');
cout << keyIndex1 << " " << KeyIndex2 << " " << keyIndex3;
}
// assume the binary search is completed and correct, what should be printed out?
Please explain, thank you.
Explanation / Answer
The output ::
0 -1 4
The binary search function searches for a given key on an array chars[] and returns the index of the search key if found otherwise returns -1.
Binary search is performed on a sorted array.
First it check the middle element, if middle is greater than key, the binarysearch is called recursively with array from start to half the size, half the size,key as parameters.
if middle is less than key, the binarysearch is called from middle to size of array, half the size,key as parameters.
This is done untill key is found or array size becomes zero.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.