Check if an Array is Sorted in C
To check if an array is sorted in C, we need to iterate through the array and verify that each element is less than or equal to the next element. If we find an element that is greater than the next one, the array is not sorted. Otherwise, it is sorted.
Examples to Check if an Array is Sorted
1. Checking if an Array is Sorted Using a for
Loop
In this example, we will use a for
loop to check whether the elements in an array are sorted in ascending order.
main.c
</>
Copy
#include <stdio.h>
// Function to check if array is sorted
int isSorted(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
if (arr[i] > arr[i + 1]) {
return 0; // Array is not sorted
}
}
return 1; // Array is sorted
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
if (isSorted(arr, size)) {
printf("The array is sorted.\n");
} else {
printf("The array is not sorted.\n");
}
return 0;
}
Explanation:
- We define a function
isSorted()
that takes an arrayarr
and itssize
as arguments. - Using a
for
loop, we iterate from index0
tosize - 2
(to compare adjacent elements). - If we find an element
arr[i]
greater thanarr[i + 1]
, the function returns0
(not sorted). - If the loop completes without finding such an element, the function returns
1
(sorted). - In
main()
, we declare and initialize an array, calculate its size, and callisSorted()
. - Based on the return value, we print whether the array is sorted or not.
Output:
The array is sorted.
2. Checking if an Array is Sorted Using a while
Loop
In this example, we will use a while
loop instead of a for
loop to check if an array is sorted.
main.c
</>
Copy
#include <stdio.h>
// Function to check if array is sorted using while loop
int isSorted(int arr[], int size) {
int i = 0;
while (i < size - 1) {
if (arr[i] > arr[i + 1]) {
return 0; // Array is not sorted
}
i++;
}
return 1; // Array is sorted
}
int main() {
int arr[] = {5, 4, 3, 2, 1}; // Unsorted array
int size = sizeof(arr) / sizeof(arr[0]);
if (isSorted(arr, size)) {
printf("The array is sorted.\n");
} else {
printf("The array is not sorted.\n");
}
return 0;
}
Explanation:
- We use the same logic as in the first example but replace the
for
loop with awhile
loop. - The loop starts with
i = 0
and runs whilei < size - 1
. - If an element
arr[i]
is greater thanarr[i + 1]
, the function returns0
(not sorted). - Otherwise, we increment
i
and continue checking until the end of the array. - If no unordered pair is found, the function returns
1
(sorted).
Output:
The array is not sorted.
Conclusion
In this tutorial, we explored different ways to check if an array is sorted in C:
- Using a
for
loop: A straightforward way to check each pair of elements. - Using a
while
loop: Works similarly but with a different control structure.
Both approaches efficiently determine whether an array is sorted by making a single pass through the array.