Algorithms | Searching | Question 4

Last Updated :
Discuss
Comments

Consider the following C program that attempts to locate an element x in an array Y[] using binary search. The program is erroneous.

C
   f(int Y[10], int x) {
     int i, j, k;
     i = 0; j = 9;
     do {
             k =  (i + j) /2;
             if( Y[k] < x)  i = k; else j = k;
         } while(Y[k] != x && i < j);
     if(Y[k] == x) printf ("x is in the array ") ;
     else printf (" x is not in the array ") ;
 }
Java
public class Main {
    public static void f(int[] Y, int x) {
        int i = 0, j = 9, k;
        do {
            k = (i + j) / 2;
            if (Y[k] < x) {
                i = k;
            } else {
                j = k;
            }
        } while (Y[k] != x && i < j);
        
        if (Y[k] == x) {
            System.out.println("x is in the array");
        } else {
            System.out.println("x is not in the array");
        }
    }
}
Python
def f(Y, x):
    i, j = 0, 9
    while Y[(i + j) // 2] != x and i < j:
        k = (i + j) // 2
        if Y[k] < x:
            i = k
        else:
            j = k
    if Y[k] == x:
        print("x is in the array")
    else:
        print("x is not in the array")
JavaScript
function f(Y, x) {
    let i = 0, j = 9;
    let k;
    do {
        k = Math.floor((i + j) / 2);
        if (Y[k] < x) {
            i = k;
        } else {
            j = k;
        }
    } while (Y[k] !== x && i < j);
    
    if (Y[k] === x) {
        console.log("x is in the array");
    } else {
        console.log("x is not in the array");
    }
}

On which of the following contents of Y and x does the program fail?

Y is [1 2 3 4 5 6 7 8 9 10] and x < 10

Y is [1 3 5 7 9 11 13 15 17 19] and x < 1

Y is [2 2 2 2 2 2 2 2 2 2] and x > 2

Y is [2 4 6 8 10 12 14 16 18 20] and 2 < x < 20 and x is even

Share your thoughts in the comments