Skip to content

Commit c734c2e

Browse files
Recursion Day 3 is completed
1 parent fadf5cd commit c734c2e

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

Recursion/Sorted.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package Recursion;
2+
3+
public class Sorted {
4+
5+
static boolean isSorted(int[] arr, int n, int first, int second) { //optimized
6+
if(n<0)
7+
return true;
8+
if(arr[first]>arr[second])
9+
return false;
10+
return isSorted(arr, n-1, first+1, second+1);
11+
}
12+
13+
static boolean issorted(int[] arr,int index) {
14+
if(index==arr.length-1)
15+
return true;
16+
return arr[index]<=arr[index+1] && issorted(arr, index+1);
17+
}
18+
public static void main(String[] args) {
19+
int arr[] = {2,6,8,8}, n = arr.length;
20+
System.out.println(isSorted(arr,n-2,0,1));
21+
System.out.println(issorted(arr, 0));
22+
}
23+
}
24+

SearchingAlgorithm/LinearSearch.java

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,39 @@ static String linearSearch(int a[],int n,int t){
1010
return "Founded";
1111
return "NotFounded";
1212
}
13+
14+
static boolean recursiveLinearSearch(int a[],int index, int target) {
15+
if(index == a.length-1)
16+
return false;
17+
return a[index]==target || recursiveLinearSearch(a, index+1, target);
18+
}
19+
20+
21+
//Example a[] = {1,23,5,5,10}
22+
static int recursiveLinearSearchForward(int a[],int index, int target) {
23+
if(index == a.length-1)
24+
return -1;
25+
if(a[index]==target)
26+
return index;
27+
return recursiveLinearSearchForward(a, index+1, target);
28+
} //it return index as 2
29+
static int recursiveLinearSearchBackward(int a[],int index, int target) {
30+
if(index == -1)
31+
return -1;
32+
if(a[index]==target)
33+
return index;
34+
return recursiveLinearSearchBackward(a, index-1, target);
35+
} //it return index as 3
36+
37+
// if we have multiple occurs in search array if you need two value index added in the new array list
38+
1339
public static void main(String[] args) {
14-
int a[]={11,3,55,6,7,355,77};
15-
int target=15;
40+
int a[]={11,3,55,55,6,7,355,77};
41+
int target=55;
1642
int n=a.length;
1743
System.out.println(linearSearch(a,n,target));
44+
System.out.println(recursiveLinearSearch(a,0,target));
45+
System.out.println(recursiveLinearSearchForward(a,0,target));
46+
System.out.println(recursiveLinearSearchBackward(a,n-1,target));
1847
}
1948
}

0 commit comments

Comments
 (0)