This is the question : An array is sorted (in ascending order) if each element of the array is less than or equal to the next element.
Write a boolean-valued method named isSorted that accepts an integer array, and the number of elements in the array and returns whether the array is sorted.
Before showing the code : my logic is that an if else-if and else statement should first determine if the size of the array is 0,1,or 2. This is because when the size equals 1 or 2, the program must break. When the size is larger than 2, the program should check arr[size-1] > arr[size-2] and then call the method again with size decremented if that is true and just return false if it is untrue. When I ran that program, the following 2 tests failed : [1,3,2,4] and [2,1,2,3,4]. Because of this I specified that when the size is equal to 2, the method returns false if arr[0] > arr[1] however it didn't work. What am I doing wrong? I don't want to just look up the answer because I am studying for a test so I am sorry if there are repeated answers.
I know the loop is better I just wanted to study recursion
public boolean isSorted(int[] arr, int size) {
if(size == 0 || size == 1) {
return true;
} else if (size == 2) { //this is the part I don't get.
if (arr[0] > arr[1]) {
return false;
} else {
isSorted(arr,size-1);
return true;
}
} else {
if (arr[size-1] < arr[size-2]) {
return false;
} else {
isSorted(arr, size-1);
return true;
}
}
}