adplus-dvertising
frame-decoration

Question

Choose among the following code for an iterative binary search.
a)

public static int iterative(int arr[], int key)
{
 int low = 0;
 int mid = 0;
 int high = arr.length-1;
 while(low <= high)
 {
  mid = low + (high + low)/2;
  if(arr[mid] == key)
  {
   return mid;
  }
  else if(arr[mid] < key)
  {
   low = mid - 1;
  }
  else
  {
   high = mid + 1;
  }
 }
 return -1;
}

b)

public static int iterative(int arr[], int key)
{
 int low = 0;
 int mid = 0;
 int high = arr.length-1;
 while(low <= high)
 {
  mid = low + (high - low)/2;
  if(arr[mid] == key)
  {
   return mid;
  }
  else if(arr[mid] < key)
  {
   low = mid + 1;
  }
  else
  {
   high = mid - 1;
  }
 }
 return -1;
}

c)

public static int iterative(int arr[], int key)
{
 int low = 0;
 int mid = 0;
 int high = arr.length-1;
 while(low <= high)
 {
  mid = low + (high + low)/2;
  if(arr[mid] == key)
  {
   return mid;
  }
  else if(arr[mid] < key)
  {
   low = mid + 1;
  }
  else
  {
   high = mid - 1;
  }
 }
 return -1;
}

d) None of the mentioned

a.

a

b.

b

c.

c

d.

d

Answer: (b).b

Engage with the Community - Add Your Comment

Confused About the Answer? Ask for Details Here.

Know the Explanation? Add it Here.

Q. Choose among the following code for an iterative binary search.

Similar Questions

Discover Related MCQs

Q. Binary Search can be categorized into which of the following?

Q. Given an array arr = {5,6,77,88,99} and key = 88; How many iterations are done until the element is found?

Q. Given an array arr = {45,77,89,90,94,99,100} and key = 100; What are the mid values(corresponding array elements) generated in the first and second iterations?

Q. What is the time complexity of binary search with iteration?

Q. When is the uniform binary search an optimization over the usual binary search?

Q. Given delta[4] is a global array and number of elements in the sorted array is 10, what are the values in the delta array?

Q. What is the time complexity of uniform binary search?

Q. Given, arr = {1,3,5,6,7,9,14,15,17,19} key = 17 and delta = {5,3,1,0}
How many key comparisons are made?(exclude the comparison used to decide the left or right sub array)

Q. How can Jump Search be improved?

Q. Which of the following false about Jump Search?

Q. Which algorithmic technique does Fibonacci search use?

Q. Choose the recursive formula for the Fibonacci series.(n>=1)

Q. What is the time complexity of Fibonacci Search?

Q. What are the advantages of Fibonacci Search?

Q. What is the length of the step in jump search?

Q. What is the time complexity of Jump Search?

Q. What is an in-place sorting algorithm?

Q. In the following scenarios, when will you use selection sort?

Q. What is the worst case complexity of selection sort?

Q. What is the advantage of selection sort over other sorting techniques?