Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Check if Array is Sorted (Ascending)

Check nondecreasing order in a list by comparing neighbors. Students use a boolean flag, stop on the first inversion, and understand how ties are handled.

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

In this one

  • Detect neighboring inversions
  • Accept equal neighbors
  • Stop after a failure

How it works

  1. 1

    Initialize is_sorted true.

  2. 2

    Compare each entry with its next neighbor.

  3. 3

    Clear the flag and break on a downward pair.

Edge cases

Does [2, 2, 3] pass?

Does [2, 2, 3] pass?

Yes. Equal neighbors do not violate the rule.

Does an empty list pass?

Does an empty list pass?

Yes. There are no violating pairs.

What's going on

The array is accepted unless a neighboring pair goes downward. The test arr[i] > arr[i + 1] detects exactly that violation.

Equal neighbors are allowed, so ascending here means nondecreasing rather than strictly increasing. The loop stops before the last index to keep i + 1 valid. Once a violation is found, break avoids unnecessary later comparisons.

Does [2, 2, 3] pass? Yes. Equal neighbors do not violate the rule.

Does an empty list pass? Yes. There are no violating pairs.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which pair breaks ascending order?

Pick an answer to check it.

Question 2

Does [2, 2, 3] pass?

Pick an answer to check it.

Questions people ask

Does [2, 2, 3] pass?

Yes. Equal neighbors do not violate the rule.

Does an empty list pass?

Yes. There are no violating pairs.

Which pair breaks ascending order?

A left value greater than the next.