1

I'm sorry for the stupid question, I have been searching about how to use binarysearch with my ArrayList like this :

List<Integer> arrList = new ArrayList<Integer>();       
        arrList.add(3); 
        arrList.add(5); 
        arrList.add(7);
        arrList.add(2);

The problem is when I use :

Collections.sort(arrList);
Collections.reverse(arrList);
int indeks = Collections.binarySearch(arrList, 7);

the value of indeks is always -5, I thought it should be 2 because after reversing myArrList the output looks like this :

[7, 5, 3, 2]

So what should I do here in order to get the right indeks of 7...? Thanks in advance

2
  • 1
    What does the javadoc of binarySearch say? Commented Jun 7, 2016 at 2:18
  • mmmm.. .I didn't read it ... :v Commented Jun 7, 2016 at 2:28

2 Answers 2

2

Collections.binarySearch() expects elements to be in ascending order:

The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined.

If you want to do a binary search on a descending list, use Comparator.reverseOrder():

int indeks = Collections.binarySearch(arrList, 7, Comparator.reverseOrder());

indeks is now 0, corresponding to the first element of the list.

Note that you can use the same comparator to sort the list descending, instead of sorting ascending and then reversing:

Collections.sort(arrList, Comparator.reverseOrder());
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mr. Shmosel... :)
0

binarySearch() results are undefined if the list is not sorted in ascending order. By reversing your list, it's sorted in descending order, hence the results you're seeing.

From the Javadoc:

The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined.

1 Comment

Thank you for your answer Mr.Robby.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.