static ArrayList<Integer> LinearSearch(int[] arr,int index,int target) {
ArrayList<Integer> iList = new ArrayList<>();
if(index == arr.length){
return iList;
}
if(arr[index] == target){
iList.add(index);
}
ArrayList<Integer> temp = LinearSearch(arr,index+1,target);
iList.addAll(temp);
return iList;
}
Above code is my instructors code. I don't understand the temp part. How the indexes are adding to temp? example arr = 1,2,3,4,3: it should return 4,2 but it returns 2,4.
How is this possible? I can't understand. What is going on with the stack? Please help me to understand.
Below is my own code, which I understand. Here we collect items. But I can't understand the above code.
static ArrayList<Integer> LinearSearch(int[] arr,int index,int target) {
ArrayList<Integer> iList = new ArrayList<>();
if(index == arr.length){
return iList;
}
iList = LinearSearch(arr,index+1,target);
if(arr[index] == target){
iList.addFirst(index);
}
return iList;
}
tempcaptures the array list that the recursive call returns: it contains the matching indices, but only from the given index (index+1) onward. WithaddAllall these matching indices are appended to (after!) the content we already have. The content we already have is either an empty list, or (if the current index has a match) it has one element, which isindex. AsaddAlladds indices after that first element, and those additional indices are guaranteed to be at leastindex+1(as the recursive call only looks from that index onward), we can be certain thatiListwill have the indices in increasing order.Notice where your code is different. In essence you first make the recursive calls and collect the indices it returns, and only then you check whether the current index
indexhas a matching value, and add it before those if it matches (not after). But the result is the same as with the instructor's code because these two changes cancel eachother out:If we were to take your instructor's code and just change the order of adding the recursive results with the (optional) adding of the
index...:...then the result for the example input will be
4,2. Notice that here we haveiList.add(index)and notiList.addFirst(index), and so the order is reversed to4,2.