-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind.java
More file actions
79 lines (73 loc) · 2.63 KB
/
Find.java
File metadata and controls
79 lines (73 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.aniketh;
// Very important lines of code to understand recursion in searching.
import java.lang.reflect.Array;
import java.util.ArrayList;
// This code is clear example of using linear search in recursion in boolean and int ways.
public class Find {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 3, 5, 6, 8};
// Below both the procedure to print the solution will work.
// System.out.println(findAllIndex2(arr, 3, 0, new ArrayList<>()));
ArrayList<Integer> ans = findAllIndex3(arr,3,0);
System.out.println(ans);
}
static boolean LinearRecursion(int[] arr, int target, int index) {
if (index == arr.length) {
return false;
}
return arr[index] == target || LinearRecursion(arr, target, index+1);
}
static int findIndex(int[] arr, int target, int index) {
if (index == arr.length) {
return -1;
}
if (arr[index] == target) {
return index;
} else {
return findIndex(arr, target, index + 1);
}
}
static int findIndexLast(int[] arr, int target, int index) {
if (index == -1) {
return -1;
}
if (arr[index] == target) {
return index;
} else {
return findIndexLast(arr, target, index - 1);
}
}
static ArrayList<Integer> list = new ArrayList<>();
static void findAllIndex(int[] arr, int target, int index) {
if (index == arr.length) {
return;
}
if (arr[index] == target) {
list.add(index);
}
findAllIndex(arr, target, index + 1);
}
// Code to understand how to add a target element in a list using recursion.
static ArrayList<Integer> findAllIndex2(int[] arr, int target, int index, ArrayList<Integer> list) {
if (index == arr.length) {
return list;
}
if (arr[index] == target) {
list.add(index);
}
return findAllIndex2(arr, target, index+1, list);
}
// Don't use this approach because this is not that optimised and it's making new list everytime.
static ArrayList<Integer> findAllIndex3(int[] arr, int target, int index) {
ArrayList<Integer> list = new ArrayList<>();
if (index == arr.length) {
return list;
}
if (arr[index] == target) {
list.add(index);
}
ArrayList<Integer> ansFromBelowCalls = findAllIndex3(arr, target, index+1);
list.addAll(ansFromBelowCalls);
return list;
}
}