nkh*_*kar 2 java arrays recursion binary-search
以下代码应该对卡片数组中的卡片进行递归二分搜索。Eclipse 给出一个错误,指出该方法不返回整数。
public static int binaryrSearch(Card[] cards, Card target , int low , int high)
{
if (high<low)
{
return -1;
}
int mid = (low+high)/2;
int comp = cards[mid].compareTo(target);
if(comp==0)
{
return mid;
}else if(comp<0)
{
return binaryrSearch(cards , target , mid+1 , high);
}else if (comp>0)
{
return binaryrSearch(cards , target , low , mid-1);
}
}
Run Code Online (Sandbox Code Playgroud)
比较方法:
public int compareTo(Card that){
if(this.suit<that.suit)
{
return -1;
}
if(this.suit>that.suit)
{
return 1;
}
if(this.rank<that.rank)
{
return -1;
}
if(this.rank>that.rank)
{
return 1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
comp由于您的 if-else-if 语句涵盖了(comp==0和comp<0)的所有可能值comp>0,因此您应该更改最后一个 else if :
else if (comp>0)
Run Code Online (Sandbox Code Playgroud)
其他:
else
Run Code Online (Sandbox Code Playgroud)
这样编译器就会意识到你的方法总是返回一个值。
...
if (comp==0) {
return mid;
} else if (comp<0) {
return binaryrSearch(cards , target , mid+1 , high);
} else {
return binaryrSearch(cards , target , low , mid-1);
}
...
Run Code Online (Sandbox Code Playgroud)