使用 Collections.reverseOrder() 作为比较器的 Collections.binarySearch() 返回 -1

问题描述 投票:0回答:1


package com.core.java.collections;

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

public class CollectionsBinarySearch {
     public static void main(String[] args) {
         List<Integer> al = new ArrayList<Integer>();
         al.add(10);
         al.add(20);
         al.add(30);
         al.add(40);
         al.add(50);

         // The last parameter specifies the comparator
         // method used for sorting.
         int index = Collections.binarySearch(
             al, 50, Collections.reverseOrder());

         System.out.println("Found at index " + index);
 
    }
}

上面的程序返回搜索索引为-1。二进制搜索应该返回列表中“50”的位置。然而它返回的索引为-1。请帮忙

java collections
1个回答
0
投票

要使用

Collection.binarySearch()
,您的数据必须按给定的比较器进行排序。如果不是,那么输出将是未定义的。

您已经给出了比较器

Collections.reverseOrder()
,因此您的数据必须按
Collections.reverseOrder()
排序
所以在进行二分搜索之前

Collections.sort(al, Collections.reverseOrder());

然后应用它,你的答案将是

在索引 0 处找到

正确的数据为:50,40,30,20,10。

© www.soinside.com 2019 - 2024. All rights reserved.