Check if Array is Sorted (Descending)
Check nonincreasing order in a list with adjacent comparisons. Students identify the first upward step and see why descending order can include equal neighbors.
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 sorted descending8is_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 descending order")16else:17 print("Array is not sorted")
Output
Enter array size: 5 Element 1: 9 Element 2: 7 Element 3: 5 Element 4: 3 Element 5: 1 Array is sorted in descending order
In this one
- Detect an upward step
- Define nonincreasing order
- Avoid out-of-range neighbors
How it works
- 1
Initialize is_sorted true.
- 2
Scan neighboring pairs below the final index.
- 3
Clear the flag on any left-smaller-than-right pair.
Edge cases
Does [3, 3, 1] pass?
Does [3, 3, 1] pass?
Yes. It never rises.
Does a one-element list pass?
Does a one-element list pass?
Yes. No comparison is needed.
What's going on
is_sorted starts true. A pair with arr[i] < arr[i + 1] proves the list rises somewhere and sets the flag false.
The strict violation test allows equal adjacent values. Empty and one-element lists contain no violating pair and pass. break ends the scan as soon as failure is known; the program does not sort or otherwise repair the data.
Does [3, 3, 1] pass? Yes. It never rises.
Does a one-element list pass? Yes. No comparison is needed.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which pair violates the rule?
Pick an answer to check it.
Question 2
Does [3, 3, 1] pass?
Pick an answer to check it.
Questions people ask
Does [3, 3, 1] pass?
Yes. It never rises.
Does a one-element list pass?
Yes. No comparison is needed.
Which pair violates the rule?
A left value smaller 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