Check if Array is Sorted - Optimal Solution

Check if Array is Sorted - Optimal Solution

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.

Check if Array is Sorted - Optimal Approach 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))

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.