java顺序搜索的Helper方法
我需要在递归顺序搜索arraylist时使用helper方法 以下是我的助手方法:java顺序搜索的Helper方法,java,recursion,arraylist,Java,Recursion,Arraylist,我需要在递归顺序搜索arraylist时使用helper方法 以下是我的助手方法: private int seqSearchRecHelper(int sku, int index) { if (index < inventory.size()) { if (sku == inventory.get(index).getSku()) { return index; } return seqSearchRecH
private int seqSearchRecHelper(int sku, int index) {
if (index < inventory.size()) {
if (sku == inventory.get(index).getSku()) {
return index;
}
return seqSearchRecHelper(sku, index + 1);
}
return -1;
}
它首先调用0的
seqSearchRecHelper
,因为0是第一个索引。然后,helper方法将调用自身,直到找到项或到达末尾,索引将在调用链中向上传递。当一个简单的for循环可以完成任务时,为什么要使用递归?这是一个学校作业,我们正在学习递归。那么,这是一个使用递归的坏例子。。。。但是作为一个提示,想想第一个要搜索的索引是什么。同意,它是O(n)表示内存。顺序搜索只会搜索第一个索引,对吗?然后继续下一个,直到找到正确的。
public InventoryItem seqSearchRec(int sku) {
int index = seqSearchRecHelper(sku,0);// send the key to be searched(sku)
//and the start index(lets begin with index 0)
if(index == -1){
// sku not found
}else{
// sku found at possition index
}
// return InventoryItem object
}
public InventoryItem seqSearchRec(int sku) {
int i = seqSearchRecHelper(sku, 0);
//returns null if the item is not found.
if (i == -1) return null;
return inventory.get(i);
}
public InventoryItem seqSearchRec(int sku) {
int index = seqSearchRecHelper(sku,0);// send the key to be searched(sku)
//and the start index(lets begin with index 0)
if(index == -1){
// sku not found
}else{
// sku found at possition index
}
// return InventoryItem object
}