Skip to content

Commit c3e402b

Browse files
authored
Create FirstIndexOfEle.java
1 parent bf02a1b commit c3e402b

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 first index of integer x present in the array. Return -1 if it is not present in the array.
3+
First index means, the index of first occurrence of x in the input array. Do this recursively. Indexing in the array starts from 0.
4+
5+
Input Format :
6+
Line 1 : An Integer N i.e. size of array
7+
Line 2 : N integers which are elements of the array, separated by spaces
8+
Line 3 : Integer x
9+
10+
Output Format :
11+
first index or -1
12+
13+
Constraints :
14+
1 <= N <= 10^3
15+
16+
Sample Input :
17+
4
18+
9 8 10 8
19+
8
20+
Sample Output :
21+
1
22+
*/
23+
24+
25+
public class FirstIndexOfEle {
26+
27+
public static int firstIndex(int input[], int x) {
28+
return firstIndex(input,x,0);
29+
}
30+
31+
public static int firstIndex(int input[], int x, int si)
32+
{
33+
if (si==input.length-1)
34+
{
35+
if (input[si]==x)
36+
{
37+
return si;
38+
}
39+
else
40+
{
41+
return -1;
42+
}
43+
}
44+
45+
if (input[si]==x)
46+
{
47+
return si;
48+
}
49+
50+
int smallIdx=firstIndex(input,x,si+1);
51+
return smallIdx;
52+
}
53+
54+
}

0 commit comments

Comments
 (0)