GATE | GATE CS 1996 | Question 66

Last Updated :
Discuss
Comments

Consider the following program that attempts to locate an element x in a sorted array a[ ] using binary search. Assume N>1. The program is erroneous. Under what conditions does the program fail?

C++
#include <iostream>
#include <vector>
using namespace std;

int find(vector<int>a, int n) {
    int i = 1, j = n;
    int x;
    do {
        int k = (i + j) / 2;
        if (a[k] < x) i = k + 1;
        else j = k;
    } while (a[k] != x && i < j);
    
    if (a[k] == x)
        cout << "x is in the array" << endl;
    else
        cout << "x is not in the array" << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>

int find(int a[], int n, int x) {
    int i = 1, j = n;
    int k;
    do {
        k = (i + j) / 2;
        if (a[k] < x) i = k + 1;
        else j = k;
    } while (a[k] != x && i < j);
    
    if (a[k] == x)
        printf("x is in the array\n");
    else
        printf("x is not in the array\n");
    return 0;
}
Java
import java.util.List;

public class Main {
    public static void find(int arr[], int n, int x) {
        int i = 0, j = n;
        int k;
        do {
            k = (i + j) / 2;
            if (arr[k] < x) i = k + 1;
            else j = k;
        } while (i < j && arr[k] != x);

        if (arr[k] == x)
            System.out.println("x is in the array");
        else
            System.out.println("x is not in the array");
    }
}
Python
def find(a, n, x):
    i = 0
    j = n
    while i < j:
        k = (i + j) // 2
        if a[k] < x:
            i = k + 1
        else:
            j = k
    
    if i < len(a) and a[i] == x:
        print("x is in the array")
    else:
        print("x is not in the array")
JavaScript
function find(a, n, x) {
    let i = 0, j = n;
    let k;
    do {
        k = Math.floor((i + j) / 2);
        if (a[k] < x) i = k + 1;
        else j = k;
    } while (a[k] !== x && i < j);
    
    if (a[k] === x)
        console.log("x is in the array");
    else
        console.log("x is not in the array");
}


x is the last element of the array a[]

x is greater than all elements of the array a[]

Both of the Above

x is less than the last element of the array a[]

Share your thoughts in the comments