Skip to content

Commit 022e9b2

Browse files
authored
Create LastIndexOfEle.java
1 parent c3e402b commit 022e9b2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array.
3+
Last index means - if x is present multiple times in the array, return the index at which x comes last in the array.
4+
You should start traversing your array from 0, not from (N - 1). Do this recursively. Indexing in the array starts from 0.
5+
6+
Input Format :
7+
Line 1 : An Integer N i.e. size of array
8+
Line 2 : N integers which are elements of the array, separated by spaces
9+
Line 3 : Integer x
10+
11+
Output Format :
12+
last index or -1
13+
14+
Constraints :
15+
1 <= N <= 10^3
16+
17+
Sample Input :
18+
4
19+
9 8 10 8
20+
8
21+
Sample Output :
22+
3
23+
*/
24+
25+
26+
public class LastIndexOfEle {
27+
28+
public static int lastIndex(int input[], int x) {
29+
return lastIndex(input,x,input.length-1);
30+
}
31+
32+
public static int lastIndex(int input[], int x, int li)
33+
{
34+
if (li==0)
35+
{
36+
if (input[li]==x)
37+
{
38+
return 0;
39+
}
40+
else
41+
{
42+
return -1;
43+
}
44+
}
45+
46+
if (input[li]==x)
47+
{
48+
return li;
49+
}
50+
int smallOutput=lastIndex(input,x,li-1);
51+
return smallOutput;
52+
}
53+
54+
}

0 commit comments

Comments
 (0)