【问题标题】:Why is built in Java BinarySearch returning only negative indices?为什么内置 Java BinarySearch 只返回负索引?
【发布时间】:2019-02-17 01:39:45
【问题描述】:

给定带有参数 (a,b) 的 State 对象,我想使用 java 的 binarysearch 方法来快速定位数组中的 State。状态应该首先通过增加“a”值来排序,然后如果存在平局,则增加“b”值。此外,为简单起见,所有州都是不同的。

目标是找出有多少对状态具有相反的参数值,或者满足:

State 1 = (a,b)
State 2 = (b,a)

下面的测试数据应该输出1,将States 1和State 3配对在一起。 但是,我的输出为 0,调试显示我所有的搜索都返回了负值。显然他们中的两个应该是积极的

主要方法:

/*
Test data (each state on a new line):
320 141
78 517
141 320
63 470
40 312
381 141
*/

    State[] states = new State[n];

    //Read in input (not shown)
    Arrays.sort(states);

    int ret = 0;

    for (int i = 0; i < n; i++) {
        State other = new State(states[i].b,states[i].a);
             //search for state with opposite parameters

        int index = Arrays.binarySearch(states, other);

        System.out.println(index); //debugging purposes

        if (index > -1)
            ret++;
    }


    System.out.println(ret/2); //avoid doublecounting (a/b and b/a)

状态类:

static class State implements Comparable<State> {
    int a,b; //State parameters

    public State(int a, int b) {
        this.a=a;
        this.b=b;
    }
    public int compareTo(State other) {
        if (this.a > other.a) //first sort by "a" values
            return 1;
        else if (this.a == other.a && this.b > other.b) //"a" tie, now sort by "b"
            return 1;
        else 
            return -1; 
    }
}

调试产生以下索引:

-5
-7
-7
-6
-5
-5

谁能找到问题所在?

我很确定它不是重复的。那里的海报没有事先对他的数组进行排序,并且在他的 bsearch 键中包含空格。

【问题讨论】:

    标签: java search binary-search


    【解决方案1】:

    您的compareTo 方法已损坏。合同规定this.compareTo(this) 应该返回0。你的实现永远不会返回0

    错误的comparecompareTo 方法很容易导致数组排序错误,和/或导致二分查找失败。有了这个具体的故障,很可能是后者。只有当compareTo 方法返回零时,二分查找才能“找到”一个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2018-01-29
      • 2020-04-01
      相关资源
      最近更新 更多