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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Check sorted8is_sorted = True9for i in range(len(arr) - 1):10 if arr[i] > arr[i + 1]:11 is_sorted = False12 break1314if 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
Initialize is_sorted true.
- 2
Compare each entry with its next neighbor.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum