An array is sorted (in ascending order) if each element of the array is less than or equal to the next element.

1
An array  is sorted (in ascending order) if each element of the array is less than  or equal to the next element.

LANGUAGE: JAVA

CHALLENGE:

An array is sorted (in ascending order) if each element of the array is less than or equal to the next element.
• An array of size 0 or 1 is sorted
• Compare the first two elements of the array ; if they are out of order, the array is not sorted; otherwise, check the if the rest of the array is sorted.
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.

SOLUTION:

public static boolean isSorted(int[] array){
    if(array.length == 0 || array.length == 1)
        return true;
    for(int i=0; i<array.length-1; i++) {
	if(array[i]<=array[i+1])
	    continue;
	else
	    return false;
    }
	
    return true;
}

One comment

Add comment