这是我搜索Item = a [4] = 5的二进制搜索程序如何在不声明循环外的return语句的情况下返回if中存在的值。
package Array;
/*
name Hafiz Shahir Zain
Fuuast karachi
This is the Binary Search program i search for Item=a[4]=5
*/
class myArray
{
int a[]= {1,2,3,4,5,6,7,8,9,10};
{ //this block is only for printing the array
for(int i=0; i<=9;i++)
{
System.out.println(a[i]);
}
}
public int LocationFinder()
{
int Start=a[0],End=a[9],Item=a[4],loc=0;
while(Start<=End)
{
int mid=(Start+End)/2;
if(Item==mid)
{
Item=loc;
return loc; //i wanna return location from but the error is occur how can i get ride from this error???
}
else if(Item>mid)
{
Start=mid+1;
}
else
End=mid-1;
}
}
答案 0 :(得分:0)
您的方法应如下所示:
使用索引:
public int LocationFinder()
{
int Start=0,End=arr.length - 1,Item=a[4];
//Item = key
while(Start<=End)
{
int mid=Start + (End-Start)/2;
//Checking if item is present at mid
if(arr[mid]==Item)
{
return mid; //returning the index
}
//if item is greater, than ignore the left side
else if(arr[mid]<Item)
{
Start=mid+1;
}
//if item is smaller, than ignore the right side
else
End=mid-1;
}
//returning -1 if the value is not found
return -1;
}
使用值:
public int LocationFinder()
{
int Start=arr[0],End=arr[length - 1],Item=a[4];
//Item = key
while(Start<=End)
{
int mid=(Start + End)/2;
//Checking if item is present at mid
if(arr[mid]==Item)
{
return mid; //returning the index
}
//if item is greater, than ignore the left side
else if(arr[mid]<Item)
{
Start=mid+1;
}
//if item is smaller, than ignore the right side
else
End=mid-1;
}
//returning -1 if the value is not found
return -1;
}
以备将来帮助看到: