我正在尝试对找到最后一次出现的目标的数组执行线性搜索。我被卡住了,因为我的搜索只找到目标的第一次出现而不是最后一次出现。
/** Recursive linear search that finds last occurrence of a target in the array not the first
*
* @param items The array
* @param target the item being searched for
* @param cur current index
* @param currentLength The current length of the array
* @return The position of the last occurrence
*/
public static int lineSearchLast(Object[] items, Object target, int cur, int currentLength){
if(currentLength == items.length+1)
return -1;
else if (target.equals(items[cur])&& cur < currentLength)
return cur;
else
return lineSearchLast(items, target, cur +1, currentLength);
}
public static void main (String[] args){
Integer[] numbers5 = {1,2,4,4,4};
int myResult = lineSearchLast(numbers5, 4, 0, 5);
System.out.println(myResult);