An array is sorted in ascending order if each element of the
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
Here is the C++ code for you:
bool isSorted(int[] array, int length)
{
if(length == 0 || length == 1)
return true;
for(int i = 0; i < length - 1; i++)
if(array[i] > array[i+1])
return false;
return true;
}
