⬅ Previous Topic
Reverse Array using Two PointersNext Topic ⮕
Remove Duplicates from Sorted Array⬅ Previous Topic
Reverse Array using Two PointersNext Topic ⮕
Remove Duplicates from Sorted ArrayTopic Contents
Given an array of integers, determine whether the array is sorted in strictly non-decreasing (ascending) order.
i
, the condition arr[i] ≤ arr[i+1]
holds.Return true
if the array is sorted, otherwise return false
.
arr
.n - 2
.i
, check if arr[i] > arr[i + 1]
.false
(array is not sorted).true
.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))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | If the array is not sorted and the first pair is unsorted, the algorithm returns immediately. |
Average Case | O(n) | The loop may check several elements before detecting disorder in a random unsorted array. |
Average Case | O(n) | If the array is fully sorted, the algorithm needs to scan all elements from index 0 to n - 2. |
O(1)
Explanation: The algorithm uses only constant space for the loop counter and comparisons, without any additional data structures.
Let's check if the following array is sorted in ascending order.
Compare 10
and 20
.
10 ≤ 20 → OK
Compare 20
and 30
.
20 ≤ 30 → OK
Compare 30
and 40
.
30 ≤ 40 → OK
Compare 40
and 50
.
40 ≤ 50 → OK
Array is sorted.
⬅ Previous Topic
Reverse Array using Two PointersNext Topic ⮕
Remove Duplicates from Sorted ArrayYou 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.