I am trying to check an array if it’s sorted with specific introductions. There must be at least one element in array that is greater than 0. If the array is sorted as big numbers to small it must return true and all the elements must be different in that array. So here is my code;
public class BubbleSort{
public static boolean isSorted(int[] array) {
for (int i = 0; i < array.length - 1; i++){
if(array[i] > 0 && array[i] > array[i + 1]){
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] array = {1,-3,-3};
System.out.println(isSorted(array));
}
}
In my opinion this should return false and I don’t know where it gets wrong. When it’s the same element it should return false but this code returns true.
>Solution :
So when using "Return" it, well, returns a value and stops the function.
In your case it will start at 1, looks if it is greater than 0 (Which it is) and if its greater then the next value in the array (Which is -3, so true). Both true so it will return true and stop the function.
If you want to check if it is greater then 0 and if the array goes from big to small try something like this:
public static boolean isSorted(int[] array) {
boolean foundPositive = false;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > 0) foundPositive = true;
if (array[i] <= array[i + 1]) {
return false;
}
}
return foundPositive;
}
It check if its greater then 0. Then if the number is smaller or equal to the next value, if so, return false. And when it passed that check, it will return if a number is greater then 0.