Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Check if Array is Sorted using Loop - Optimal Algorithm



Problem Statement

Given an array of integers, determine whether the array is sorted in strictly non-decreasing (ascending) order.

Return true if the array is sorted, otherwise return false.

Examples

Input ArrayIs Sorted?Description
[1, 2, 3, 4, 5]trueStrictly increasing order
[1, 2, 2, 3, 4]trueNon-decreasing (duplicates allowed)
[5, 4, 3, 2, 1]falseStrictly decreasing
[10, 20, 15, 25]falseDisorder between 20 and 15
[100]trueSingle-element array is always sorted
[]trueEmpty array is trivially sorted
[1, 3, 5, 7, 6]falseSorted until the last element breaks the order
[1, 2, 3, 3, 3]trueFlat segments are allowed in non-decreasing order

Solution

To determine if an array is sorted, we check whether each element is less than or equal to the one that comes after it. This is because in a non-decreasing (ascending) order, every element should be ≤ the next one.

What Happens in Different Cases?

  • Fully Sorted Array: If the elements go up or stay the same from left to right (like [1, 2, 2, 3, 5]), then it is sorted.
  • Unsorted Array: If there’s any element that is greater than the one after it (like [3, 5, 4]), the order is broken, and we return false.
  • Array with Duplicates: Duplicates do not break the sorting as long as the order doesn't decrease (e.g., [1, 1, 2, 2] is sorted).
  • Single-Element Array: A single number is always considered sorted since there are no comparisons to make.
  • Empty Array: An empty list has no elements out of order. So by definition, it is sorted.

This solution works by simply looping once through the array and checking every pair of neighboring elements. If we ever find a case where a number is greater than the one after it, we know the array is not sorted and can return false immediately. If we reach the end without such a case, the array is sorted.

Why This Works Efficiently

We only look at each element once, so the entire process takes O(n) time where n is the size of the array. This is the most optimal way to check for sorting.

Visualization

Algorithm Steps

  1. Given an array arr.
  2. Iterate through the array from index 0 to n - 2.
  3. For each index i, check if arr[i] > arr[i + 1].
  4. If the condition is true, return false (array is not sorted).
  5. If the loop completes without finding any such case, return true.

Code

Python
JavaScript
Java
C++
C
def is_sorted(arr):
    for i in range(len(arr) - 1):
        if arr[i] > arr[i + 1]:
            return False
    return True

# Sample Input
arr = [10, 20, 30, 40, 50]
print("Is Sorted:", is_sorted(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)If the array is not sorted and the first pair is unsorted, the algorithm returns immediately.
Average CaseO(n)The loop may check several elements before detecting disorder in a random unsorted array.
Average CaseO(n)If the array is fully sorted, the algorithm needs to scan all elements from index 0 to n - 2.

Space Complexity

O(1)

Explanation: The algorithm uses only constant space for the loop counter and comparisons, without any additional data structures.

Detailed Step by Step Example

Let's check if the following array is sorted in ascending order.

{ "array": [10,20,30,40,50], "showIndices": true }

Compare index 0 and 1

Compare 10 and 20.

1020 → OK

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndices": [0,1], "labels": {"0":"i","1":"i+1"} }

Compare index 1 and 2

Compare 20 and 30.

2030 → OK

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndices": [1,2], "labels": {"1":"i","2":"i+1"} }

Compare index 2 and 3

Compare 30 and 40.

3040 → OK

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndices": [2,3], "labels": {"2":"i","3":"i+1"} }

Compare index 3 and 4

Compare 40 and 50.

4050 → OK

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndices": [3,4], "labels": {"3":"i","4":"i+1"} }

Final Result:

Array is sorted.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M