gpt4 book ai didi

Java utils 二分搜索未找到所有值

转载 作者:行者123 更新时间:2023-12-01 08:12:31 25 4
gpt4 key购买 nike

我正在尝试在数组中搜索值,并决定使用内置的二分搜索来执行此操作。我有一个类:

import java.util.*;
public class Charge {
private int isAcct;
private int[] acctNumbers = {5658845,4520125,7895122,8777541,8451277,
1302850,8080152,4562555,5552012,5050552,7824577,
1250255,1005231,6545231,3852085,7576651,7881200,
4851002};


public Charge(int aNum) {
isAcct = aNum;
}
public Boolean isValidAcctNumber() {
int m = Arrays.binarySearch(acctNumbers, isAcct);
if (m == -1)
return false;
else
return true;
}
}

还有一个测试:

import java.util.Scanner;
public class ChargeTest {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("What is your account number?: ");
int num = scan.nextInt();
Charge charge = new Charge(num);
System.out.println(charge.isValidAcctNumber());

if (charge.isValidAcctNumber() == false) {
System.out.println("Your account "+num+" is not a valid account");
} else {
System.out.println("Your account "+num+" is a valid account");
}
}

}

这适用于某些数字,例如 4851002,但不适用于其他数字,例如 1302850。我真的不知道为什么。我很可能只会手动实现二分搜索,但我很困惑为什么这不起作用。

最佳答案

二分查找仅适用于 is already sorted 的数组.

引自Arrays.binarySearch javadoc:

Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

如果尚未排序,则它将找不到某些数字。

Sort it在尝试任何二分搜索之前:

Arrays.sort(acctNumbers);

关于Java utils 二分搜索未找到所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16179029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com