C Program to Check if an Array is Sorted

C Program to Check if an Array is Sorted

Checking whether an array is sorted is a fundamental problem in programming. Knowing if the elements in an array are in ascending or descending order is important in algorithms like binary search, sorting, and data validation. This task helps you practice working with arrays, loops, and conditional statements in C.

In this tutorial, we will write a complete C program to determine whether an array is sorted in ascending order. By the end of this article, you will understand how to check array order efficiently and confidently.

Understanding the Problem

The problem is to examine each pair of consecutive elements in the array and determine if every element is less than or equal to the next one (for ascending order). If we find even one element that violates this condition, the array is not sorted. For example, in the array [1, 2, 3, 4], every element is less than the next one, so it is sorted. But in [1, 3, 2, 4], 3 > 2 breaks the order.

This problem introduces basic array traversal and logical checks in C and prepares you for more advanced tasks like sorting algorithms and sequence validation.

Program 1: Using a Simple Loop

The easiest way to check if an array is sorted is by using a loop to compare consecutive elements.

#include <stdio.h>

int main() {

    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int isSorted = 1;  // Assume the array is sorted

    for (int i = 0; i < size - 1; i++) {

        if (arr[i] > arr[i + 1]) {
            isSorted = 0;  // Found a pair that is out of order
            break;
        }

    }

    if (isSorted) {
        printf("The array is sorted in ascending order.\n");
    } else {
        printf("The array is not sorted.\n");
    }

    return 0;

}

In this program, we first declare an array and calculate its size using sizeof(arr) / sizeof(arr[0]). We assume the array is sorted by initializing isSorted to 1 (true). The for loop checks each element with its next neighbor. If a pair violates ascending order, we set isSorted to 0 (false) and stop the loop using break. Finally, we print the result using printf().

Program 2: Using a Function

For cleaner and reusable code, you can create a function that checks if an array is sorted.

#include <stdio.h>

int checkSorted(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[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);

    if (checkSorted(arr, size)) {
        printf("The array is sorted in ascending order.\n");
    } else {
        printf("The array is not sorted.\n");
    }

    return 0;

}

The checkSorted function takes the array and its size as arguments. The logic inside the function is the same as the previous example: iterate through the array, compare consecutive elements, and return 0 if any pair is out of order. Using a function allows you to check multiple arrays without rewriting the loop each time.

Program 3: Checking for Descending Order

Sometimes, you may also need to check if the array is sorted in descending order. The logic is similar but reversed.

#include <stdio.h>

int main() {

    int arr[] = {50, 40, 30, 20, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    int isSorted = 1;

    for (int i = 0; i < size - 1; i++) {

        if (arr[i] < arr[i + 1]) {
            isSorted = 0;
            break;
        }

    }

    if (isSorted) {
        printf("The array is sorted in descending order.\n");
    } else {
        printf("The array is not sorted.\n");
    }

    return 0;

}

In this version, the if condition checks if arr[i] < arr[i + 1]. If this is true for any pair, the array is not sorted in descending order. This example shows that by simply changing the comparison operator, you can check for both ascending and descending orders.

Performance Comparison

All methods described above are efficient because they traverse the array only once. The time complexity is O(n) for all methods, and the space complexity is O(1) since no extra storage is needed. For large arrays, these methods are fast and practical.

MethodTime ComplexitySpace ComplexityNotes
Simple LoopO(n)O(1)Easiest to understand
Function ApproachO(n)O(1)Reusable and clean
Descending CheckO(n)O(1)Useful if you need descending order check

FAQs

1. Can this program check if an array is sorted in descending order?
Yes. You just need to change the comparison in the loop from > to < to detect descending order.

2. Can this method be used for floating-point numbers?
Absolutely. The same logic works for float or double arrays, with comparisons between consecutive elements.

3. What if the array has all equal elements?
An array where all elements are equal is considered sorted because each element is not greater than the next in ascending order and not smaller in descending order.

Conclusion

Checking if an array is sorted is an essential programming task that helps you understand loops, array traversal, and conditional checks. You have learned simple methods to check ascending and descending orders, as well as using a reusable function for cleaner code.

By practicing these techniques, you will gain confidence in handling arrays and preparing for more advanced tasks like searching and sorting algorithms. Always pay attention to edge cases, such as empty arrays or arrays with equal elements, to ensure your programs work correctly.

References & Additional Resources

A curated collection of textbooks and tutorials for learning arrays, functions, and basic C programming concepts.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – A classic book covering arrays, functions, and core C programming concepts.
  2. GeeksforGeeks: Check if Array is Sorted – Explains methods to verify if an array is sorted, with detailed code examples in C.
  3. Tutorialspoint: C Arrays – Overview of array operations, including declaration, initialization, and traversal.
  4. Cprogramming.com: Functions in C – Guide on writing reusable functions and using them to organize C code effectively.
  5. cplusplus.com: C Programming Basics – Beginner-friendly resource covering the fundamentals of C programming.

Scroll to Top