Code Explanation:
Function Definition
def is_sorted(arr):
Purpose: Checks if a list arr is sorted in non-decreasing order (each element is less than or equal to the next).
Base Case – List of Length 0 or 1
if len(arr) <= 1:
return True
Why: A list with 0 or 1 element is trivially sorted.
Action: Return True.
Recursive Case – Compare First Two Elements
return arr[0] <= arr[1] and is_sorted(arr[1:])
Step 1: Check if the first element is less than or equal to the second: arr[0] <= arr[1].
Step 2: Recursively check if the rest of the list arr[1:] is sorted.
Logic: The entire list is sorted only if:
The first pair is in order
The remaining sublist is also sorted
Example Call
print(is_sorted([1, 2, 3, 4, 5]))
List: [1, 2, 3, 4, 5]
Each pair of elements is in order.
Recursive calls proceed:
[2, 3, 4, 5] → [3, 4, 5] → [4, 5] → [5] → returns True
Final Output
True
The list [1, 2, 3, 4, 5] is sorted, so the function returns True.
.png)

0 Comments:
Post a Comment