Java 递归线性搜索算法
我的家庭作业是创建一个从一个索引到另一个索引的递归线性搜索算法。由于某种原因,下面的代码每次都返回-1Java 递归线性搜索算法,java,list,recursion,Java,List,Recursion,我的家庭作业是创建一个从一个索引到另一个索引的递归线性搜索算法。由于某种原因,下面的代码每次都返回-1 public static int recLinearSearch(ArrayList<String> pList, String pKey, int pBeginIdx, int pEndIdx) { if (pBeginIdx > pEndIdx) { return -1; } else if (pList.get(pBeginIdx).e
public static int recLinearSearch(ArrayList<String> pList, String pKey, int pBeginIdx, int pEndIdx) {
if (pBeginIdx > pEndIdx) {
return -1;
} else if (pList.get(pBeginIdx).equals(pKey)) {
return pList.indexOf(pBeginIdx);
}
// Recursive case
else return recLinearSearch(pList, pKey, pBeginIdx + 1, pEndIdx - 1);
}
publicstatic int-recLinearSearch(ArrayList-pList、String-pKey、int-pBeginIdx、int-pEndIdx){
if(pBeginIdx>pEndIdx){
返回-1;
}else if(pList.get(pBeginIdx).equals(pKey)){
返回pList.indexOf(pBeginIdx);
}
//递归案例
否则返回线性搜索(pList、pKey、PBEGINIX+1、pEndIdx-1);
}
我这样称呼它:
ArrayList<String> list = new ArrayList<>();
list.add("Jonathan");
list.add("Zier");
System.out.println(list.size()); // returns 2
int idx = Hw3_1.recLinearSearch(list, "Jonathan", 0, list.size() - 1);
System.out.println(idx); //returns -1
ArrayList list=new ArrayList();
列表。添加(“乔纳森”);
列表。添加(“Zier”);
System.out.println(list.size());//返回2
int idx=Hw3_1.recLinearSearch(list,“Jonathan”,0,list.size()-1);
System.out.println(idx)//返回-1
索引不是列表中的元素,因此pList.indexOf(pBeginIdx)
将始终重新运行-1
。此外,使用indexOf
有点漏掉了重点,IMHO-你应该自己实现搜索。您已正确检查元素是否等于键-只需返回它:
public static int recLinearSearch(ArrayList<String> pList, String pKey, int pBeginIdx, int pEndIdx) {
if (pBeginIdx > pEndIdx) {
return -1;
} else if (pList.get(pBeginIdx).equals(pKey)) {
return pBeginIdx; // Here!
}
// Recursive case
else return recLinearSearch(pList, pKey, pBeginIdx + 1, pEndIdx); // Don't alter the end index!
}
publicstatic int-recLinearSearch(ArrayList-pList、String-pKey、int-pBeginIdx、int-pEndIdx){
if(pBeginIdx>pEndIdx){
返回-1;
}else if(pList.get(pBeginIdx).equals(pKey)){
返回pBeginIdx;//在这里!
}
//递归案例
否则返回recLinearSearch(pList,pKey,pBeginIdx+1,pEndIdx);//不要更改结束索引!
}
我认为返回pList.indexOf(pBeginIdx)
应该是返回pBeginIdx代码>。否则,您将在字符串
对象列表中查找整数
。我把这当作一个打字错误——这似乎比张贴答案更合适。@DawoodibnKareem是正确的(ish)。因为您没有说函数应该返回索引还是元素,returnplist.get(pBeginIdx)
可能是正确的。主要问题是你修改了两个端点,但只测试了一个。现在我明白了,这是一个非常愚蠢的错误。非常感谢。我已经取消了我的投票,因为这是由两个错误造成的——我提到的一个和Tibrogargan提到的一个。你如何使用pEndIdx?这似乎没有任何用处,在每次匹配时,它会无缘无故地递减。