Check if Array is Sorted (Ascending)

Check if array is sorted in ascending order.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 1 of 14
check-if-array-is-sorted-ascending.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Check sorted
8is_sorted = True
9for i in range(len(arr) - 1):
10 if arr[i] > arr[i + 1]:
11 is_sorted = False
12 break
13
14if is_sorted:
15 print("Array is sorted in ascending order")
16else:
17 print("Array is not sorted")

Output

Enter array size: 5
Element 1: 1
Element 2: 3
Element 3: 5
Element 4: 7
Element 5: 9
Array is sorted in ascending order

What's going on

Compare each element with next.

Key Concepts:

Check if arr[i] <= arr[i+1] for all i
If any violation, not sorted
Early exit on first violation