Consider the C function given below. Assume that the array listA contains n (> 0) elements, sorted in ascending order.
#include <iostream>
using namespace std;
int ProcessArray(int *listA, int x, int n)
{
int i, j, k;
i = 0;
j = n-1;
do
{
k = (i+j)/2;
if (x <= listA[k])
j = k-1;
if (listA[k] <= x)
i = k+1;
}
while (i <= j);
if (listA[k] == x)
return(k);
else
return -1;
}
#include <stdio.h>
int ProcessArray(int *listA, int x, int n)
{
int i, j, k;
i = 0;
j = n-1;
do
{
k = (i+j)/2;
if (x <= listA[k])
j = k-1;
if (listA[k] <= x)
i = k+1;
}
while (i <= j);
if (listA[k] == x)
return(k);
else
return -1;
}
public class Main {
public static int ProcessArray(int[] listA, int x, int n) {
int i = 0, j = n - 1, k;
do {
k = (i + j) / 2;
if (x <= listA[k])
j = k - 1;
if (listA[k] <= x)
i = k + 1;
} while (i <= j);
if (listA[k] == x)
return k;
else
return -1;
}
}
def ProcessArray(listA, x, n):
i = 0
j = n - 1
while i <= j:
k = (i + j) // 2
if x <= listA[k]:
j = k - 1
if listA[k] <= x:
i = k + 1
if listA[k] == x:
return k
else:
return -1
function ProcessArray(listA, x, n) {
let i = 0;
let j = n - 1;
let k;
do {
k = Math.floor((i + j) / 2);
if (x <= listA[k])
j = k - 1;
if (listA[k] <= x)
i = k + 1;
} while (i <= j);
if (listA[k] === x)
return k;
else
return -1;
}
Which one of the following statements about the function ProcessArray is CORRECT?
It will run into an infinite loop when x is not in listA.
It is an implementation of binary search.
It will always find the maximum element in listA.
It will return −1 even when x is present in listA.
This question is part of this quiz :
Top MCQs on Searching Algorithm with Answers,GATE-CS-2014-(Set-3)