Check if Array is Sorted (Ascending)

Check if array is sorted in ascending order.

Logic BuildingAdvanced
Logic Building
# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
    arr.append(int(input(f"Element {i+1}: ")))

# Check sorted
is_sorted = True
for i in range(len(arr) - 1):
    if arr[i] > arr[i + 1]:
        is_sorted = False
        break

if is_sorted:
    print("Array is sorted in ascending order")
else:
    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

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