我认为,
我正在尝试使二进制搜索工作。它应该要求您达到一个数组大小,将整数在数组中输入,并搜索数组以找到您要寻找的数字以及找到多少探针以找到它或找到数字。我正在遵循该算法,但它要么以无限循环的响应,或者根本没有响应,因为它永远运行。有什么建议吗?
package assignment3;
import java.util.Scanner;
public class search{
public static void main(String[] arg){
Scanner range=new Scanner(System.in);
System.out.println("Pick your array size.");
int element=range.nextInt();
int[] array=new int[element];
Scanner array_list=new Scanner(System.in);
if(element<=0){
System.out.println("The array size you chose is not supported. You must chose again");
Scanner tryagain=new Scanner(System.in);
System.out.println("Try again");
element=tryagain.nextInt();
}
System.out.println("Now enter all the numbers in your array");
String list=array_list.nextLine();
String[] newlist=list.split("\ ");
int lengthofarray=newlist.length;
for(int i=0; i<lengthofarray; i++){
array[i]=Integer.parseInt(newlist[i]);
System.out.println(i+" || "+array[i]);
}
Scanner linearSearch=new Scanner(System.in);
System.out.println("Pick a number to see if it is in the array and how many times it took to find it.");
int linear=linearSearch.nextInt();
Scanner linear2=new Scanner(System.in);
System.out.println("Now we will try the same thing with a binary search. Pick a number");
int binarysearch=linear2.nextInt();
int low=0;
int high=lengthofarray-1;
int middle;
while(low<=high){
middle=(low+high)/2;
if(array[middle]>binarysearch){
high=middle-1;
}
else if(array[middle]<binarysearch){
low=middle+1;
}
}
if(array[low]==binarysearch){
System.out.println("Your number is in the array.");
}
else{
System.out.println("your number is not in the array.");
}
}
}
问题是您错过了array[middle] == binarysearch
时的情况。查看二进制搜索的逻辑,您会发现low
和high
都不会更改,并且循环永远不会终止。
而是尝试一下:
while (low <= high) {
middle = (low + high) / 2;
if (array[middle] > binarysearch) {
high = middle - 1;
} else if (array[middle] == binarysearch) {
low = middle;
break;
} else {
low = middle + 1;
}
}
/*PROGRAM FOR BINARY SEARCH*/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[100];
int a,n,i,item,loc,temp;
clrscr();
n=1;
loc=0;
printf("nEnter total no of data: ");
scanf("%d",&a);
for(i=0;i<a;i++)
{
printf("n Enter a[%d]:",i);
scanf("%d",&arr[i]);
loc=loc+1;
}
printf("nEnter ITEM u want to search:");
scanf("%d",&item);
temp=loc+1;
arr[temp]=item;
while(n<=a && arr[n]!=item)
{
n=n+1;
}
if(n==arr[temp])
{
n=0;
printf("nn=%d",n);
}
else
{
printf("n ITEM is present AT a[%d]",n);
}
getch();
}