Page 1 of 1

About Question enthuware.ocpjp.v17.2.3743 :

Posted: Wed Jul 26, 2023 8:36 am
by edufin166@yahoo.com
The answers is incorrect:

The output is:

[a, b, c]
2
[c, b, a]
-4

Therefore, the correct answer is : 2, -4

Re: About Question enthuware.ocpjp.v17.2.3743 :

Posted: Wed Jul 26, 2023 9:07 am
by admin
No, it may not necessarily print -4 for the second search statement. The API clearly says that if the list is not sorted by its natural order then the result will be undefined. So, even if it prints -4, it is not guaranteed to print -4.

Re: About Question enthuware.ocpjp.v17.2.3743 :

Posted: Wed Jul 26, 2023 9:48 am
by edufin166@yahoo.com
I run this code 10x, in Intellij...

Code: Select all

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BinarySearchTest {

  public static void main(String[] args) {

    List<String> letters = new ArrayList<String>();
    letters.addAll(List.of("a", "c", "b"));

    Collections.sort(letters);
    System.out.println(letters);
    System.out.println(Collections.binarySearch(letters, "c"));

    Collections.reverse(letters);
    System.out.println(letters);
    System.out.println(Collections.binarySearch(letters, "c"));
  }

}
And the answer is:
[a, b, c]
2
[c, b, a]
-4

But thats ok, I will consider your answers as correct.

Tahnks

Re: About Question enthuware.ocpjp.v17.2.3743 :

Posted: Wed Jul 26, 2023 9:59 am
by admin
You may run it a thousand times and it will print the same because that depends on the library code contained in the JDK that you are using. But since the API gives no guarantee the next version of the JDK may print something else. You can't depend on this output.

Re: About Question enthuware.ocpjp.v17.2.3743 :

Posted: Sun Feb 23, 2025 10:35 am
by raphaelzintec
If I have an array [1, 2, 3, 4] or a list {1, 2, 3, 4}, and they are already sorted at the time of declaration but I haven't explicitly called a sort() function, will the result of a binary search be predictable?

Re: About Question enthuware.ocpjp.v17.2.3743 :

Posted: Sun Feb 23, 2025 4:47 pm
by admin
Yes, if the elements are sorted, irrespective of whether you sorted them explicitly or not, the result of the search will be predictable.

Re: About Question enthuware.ocpjp.v17.2.3743 :

Posted: Mon Feb 24, 2025 7:05 pm
by raphaelzintec
thank you!