LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 5

Sorting and then searching Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {50, 10, 40, 20, 30};
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.binarySearch(a, 40) + " " + Arrays.binarySearch(a, 25) + " " + Arrays.binarySearch(a, 5) + " " + Arrays.binarySearch(a, 60));
    }
}
  • A [10, 20, 30, 40, 50] 3 -3 -1 -6 Correct
  • B [10, 20, 30, 40, 50] 3 -1 -1 -1
  • C [10, 20, 30, 40, 50] 4 -3 -1 -6
  • D [50, 40, 30, 20, 10] 1 -3 -6 -1
Correct Answer: Option A

A missing key returns -(insertion point) - 1: 25 would go at index 2 (-3), 5 at 0 (-1), 60 at 5 (-6).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links