Is the dataset sorted?
This is not required for the given problem, but a very simple algorithm to implement.
Function Definition: isSorted
isSorted
The function isSorted
takes a list of integers as an input and returns a boolean indicating whether the list is sorted in non-decreasing order.
array: list[int]
: This is a type annotation indicating that the parameterarray
is expected to be a list of integers.-> bool
: This indicates that the function will return a boolean value (True
orFalse
).
Base Case:
If the length of the array is 0 or 1, the function returns
True
.A list with 0 or 1 element is trivially sorted because there are no pairs of elements to compare.
Loop Through the Array:
The function iterates through the array starting from the second element (
i = 1
) to the last element (i = len(array) - 1
).Comparison:
For each index
i
, it compares the element atarray[i-1]
with the element atarray[i]
.If
array[i-1]
is greater thanarray[i]
, the function returnsFalse
immediately, indicating that the list is not sorted in non-decreasing order.
End of the For Loop:
If the loop completes without finding any elements that are out of order, the function returns
True
, indicating that the list is sorted.
Last updated