Algorithm Steps
- Given an array
arr
. - Iterate through the array from index 0 to
n - 2
. - For each index
i
, check ifarr[i] > arr[i + 1]
. - If the condition is true, return
false
(array is not sorted). - 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
.
10 ≤ 20 → 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
.
20 ≤ 30 → 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
.
30 ≤ 40 → 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
.
40 ≤ 50 → OK
{
"array": [10,20,30,40,50],
"showIndices": true,
"highlightIndices": [3,4],
"labels": {"3":"i","4":"i+1"}
}
Final Result:
Array is sorted.