How to implement the is_sorted algorithm to check if an array is sorted in increasing order in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <stddef.h>

/*
    is_sorted: Check whether an array is sorted in non-decreasing order.

    Parameters:
        arr     - pointer to the first element of the array
        n       - number of elements

    Returns:
        true  - if the array is sorted (each element <= next)
        false - otherwise

    Idiomatic C approach:
        - Use a simple loop (fast and predictable).
        - Compare each element with its successor.
        - Stop immediately when a violation is found (efficient).
*/
bool is_sorted(const int *arr, size_t n) {
    if (n < 2) {
        return true;    // Arrays of size 0 or 1 are trivially sorted
    }

    for (size_t i = 0; i < n - 1; ++i) {
        if (arr[i] > arr[i + 1]) {
            return false;   // Early exit: found a descending pair
        }
    }

    return true;            // No violations found
}

int main(void) {
    int data1[] = { 1, 2, 3, 4, 5 };     // sorted
    int data2[] = { 5, 4, 3, 2, 1 };     // not sorted
    int data3[] = { 2, 2, 3, 3, 4 };     // sorted (non-decreasing)
    int data4[] = { 10 };                // trivially sorted

    size_t size1 = sizeof(data1) / sizeof(data1[0]);
    size_t size2 = sizeof(data2) / sizeof(data2[0]);
    size_t size3 = sizeof(data3) / sizeof(data3[0]);
    size_t size4 = sizeof(data4) / sizeof(data4[0]);

    printf("data1 sorted? %s\n", is_sorted(data1, size1) ? "true" : "false");
    printf("data2 sorted? %s\n", is_sorted(data2, size2) ? "true" : "false");
    printf("data3 sorted? %s\n", is_sorted(data3, size3) ? "true" : "false");
    printf("data4 sorted? %s\n", is_sorted(data4, size4) ? "true" : "false");

    return 0;
}


/*
run:

data1 sorted? true
data2 sorted? false
data3 sorted? true
data4 sorted? true

*/

 



answered Jul 24 by avibootz

Related questions

...