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

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.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 2 of 14
check-if-array-is-sorted-descending.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 descending
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 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. 1

    Initialize is_sorted true.

  2. 2

    Scan neighboring pairs below the final index.

  3. 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.