-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCheckSortedArray.java
More file actions
57 lines (50 loc) · 1.77 KB
/
CheckSortedArray.java
File metadata and controls
57 lines (50 loc) · 1.77 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
package recursion1;
import java.util.Scanner;
public class CheckSortedArray {
public static boolean checkSorted(int[] arr) {
if (arr.length <= 1) {
return true;
}
if (arr[0] > arr[1]) {
return false;
}
/*breaking the bigger array into smaller array everytime*/
int[] smallArr = new int[arr.length - 1];
/*copying the array*/
for (int i = 1; i < arr.length; i++) {
smallArr[i - 1] = arr[i];
}
return checkSorted(smallArr);
}
/*this functions check whether the array is sorted or in the range startIndex to arr.length*/
private static boolean checkSortedOptimised(int[] arr, int startIndex) {
/*if there is only one element which is obviously sorted by default*/
if (startIndex >= arr.length - 1) {
return true;
}
/*if first element is of the array is greater than the second element its obviously sorted.*/
if (arr[startIndex] > arr[startIndex + 1]) {
return false;
}
return checkSortedOptimised(arr, startIndex + 1);
}
/*Recursion and the helper function*/
public static boolean checkSortedOptimised(int[] arr) {
return checkSortedOptimised(arr, 0);
}
public static int[] takeInput() {
Scanner scan = new Scanner(System.in);
System.out.print("Size of the Array? ");
int size = scan.nextInt();
int[] arr = new int[size];
System.out.println("Enter elements of the Array: ");
for (int i = 0; i < size; i++) {
arr[i] = scan.nextInt();
}
return arr;
}
public static void main(String[] args) {
int[] arr = takeInput();
System.out.println(checkSortedOptimised(arr));
}
}