How to check if array is already sorted

You don’t need to sort your array to check if it’s sorted. Loop over each consecutive pair of elements and check if the first is less than the second; if you find a pair for which this isn’t true, the array is not sorted.

boolean sorted = true;

for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] > arr[i+1]) {
        sorted = false;
        break;
    }
}

Leave a Comment