About Question enthuware.ocpjp.v17.2.3743 :
Moderator: admin
-
- Posts: 24
- Joined: Wed Sep 28, 2022 9:41 am
- Contact:
About Question enthuware.ocpjp.v17.2.3743 :
The answers is incorrect:
The output is:
[a, b, c]
2
[c, b, a]
-4
Therefore, the correct answer is : 2, -4
The output is:
[a, b, c]
2
[c, b, a]
-4
Therefore, the correct answer is : 2, -4
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
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.
-
- Posts: 24
- Joined: Wed Sep 28, 2022 9:41 am
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
I run this code 10x, in Intellij...
And the answer is:
[a, b, c]
2
[c, b, a]
-4
But thats ok, I will consider your answers as correct.
Tahnks
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"));
}
}
[a, b, c]
2
[c, b, a]
-4
But thats ok, I will consider your answers as correct.
Tahnks
Last edited by admin on Wed Jul 26, 2023 9:57 am, edited 1 time in total.
Reason: Please put code inside [code] [/code]
Reason: Please put code inside [code] [/code]
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
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.
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
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?
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
Yes, if the elements are sorted, irrespective of whether you sorted them explicitly or not, the result of the search will be predictable.
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
Who is online
Users browsing this forum: No registered users and 10 guests