gpt4 book ai didi

java - 二分查找的返回值

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

我创建了一个程序,它生成一个随机的 10 个数字数组,使用冒泡排序对数组进行排序,然后使用二分搜索来查看该值是否在数组中。我的所有代码对我来说看起来都是正确的,但每次我运行程序时,如果我选择搜索的数字实际上在数组中,它仍然告诉我它不是。我相信这与我的返回值有关,但代码对我来说看起来是正确的。

import java.util.Scanner;

public class BubbleSort {

public static void main(String[] args) {
final int SIZE=10;
int[] numbers= new int[SIZE];
int number;
int result;
Scanner keyboard = new Scanner(System.in);
loadArray(numbers);
sortArray(numbers);
displayArray(numbers);
System.out.print("Enter your number: ");
number=keyboard.nextInt();
result=binarySearch(numbers, number);
if(result==-1){
System.out.print("Your number was not found");
}else{
System.out.print("Your number was found");
}
}
public static void loadArray(int[] numbers){
int index;
for(index=0;index<numbers.length;index++){
numbers[index]=(int)(Math.random()*100)+1;
}
}
public static void sortArray(int[] num){
int index;
int passNo;
int holdingnumber;
//boolean condition=true;
//while(condition){
//condition=false;
for(passNo=0;passNo<num.length-1;passNo++){
for(index=0;index<num.length-1;index++){
if(num[index]>num[index+1]){
holdingnumber=num[index+1];
num[index+1]=num[index];
num[index]=holdingnumber;
//condition=true;
}
}
}

}
public static void displayArray(int[] numbers){
int index;
for(index=0;index<numbers.length;index++){
System.out.println("Element["+index+"]: " +numbers[index]);
}
}
public static int binarySearch(int[] array, int number){
int low=0;
int mid=0;
int high=0;
while(low<=high){
mid=(low+high)/2;
if(array[mid]>number){
high=mid-1;
}else if(array[mid]<number){
low=mid+1;
}else{
return mid;
}
}
return -1;
}
}

最佳答案

我认为 high 变量不等于 0 ,它需要是数组的长度,如下所示:

  int high = array.length-1;

关于java - 二分查找的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244622/

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