Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmAlgorithms | Searching | Question 4

Algorithms | Searching | Question 4

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

C




1.   f(int Y[10], int x) {
2.     int i, j, k;
3.     i = 0; j = 9;
4.     do {
5.             k =  (i + j) /2;
6.             if( Y[k] < x)  i = k; else j = k;
7.         } while(Y[k] != x && i < j);
8.     if(Y[k] == x) printf (\"x is in the array \") ;
9.     else printf (\" x is not in the array \") ;
10. }


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

(A)

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

(B)

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

(C)

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

(D)

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

Answer: (C)
Explanation:

The above program doesn’t work for the cases where the element to be searched is the last element of Y[] or greater than the last element (or maximum element) in Y[]. For such cases, the program goes in an infinite loop because i is assigned value as k in all iterations, and i never becomes equal to or greater than j. So while the condition never becomes false.

Hence Option (C) is the correct option.

Quiz of this Question
Please comment below if you find anything wrong in the above post

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments