data-structures · beginner · ~15 min

Is it sorted?

Verify an ordering invariant.

Challenge

Check whether an array is sorted in non-decreasing order.

Task

Implement int is_sorted(const int *a, int n) that returns 1 if the first n elements of a are in non-decreasing order, else 0.

Input

  • a: array of at least n ints (read-only).
  • n: the number of elements to check.

Output

int: 1 if a[0] <= a[1] <= ... <= a[n-1], else 0.

Example

{1,2,2,3}   ->   1   (equal neighbours allowed)
{1,3,2}     ->   0
{5}         ->   1

Edge cases

  • A single element (or empty array) is sorted (returns 1).
  • Equal adjacent values are allowed (non-decreasing, not strictly increasing).

Input format

a: array of at least n ints; n: element count.

Output format

int: 1 if the array is non-decreasing, else 0.

Constraints

Equal neighbours are allowed (non-decreasing).

Starter code

int is_sorted(const int *a, int n) {
    /* TODO */
    return 1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.