← All problems · Arrays & Searching
Check Whether an Array Is Sorted
Return 1 if the array is sorted in nondecreasing order. Duplicates, empty arrays and single elements are allowed.
Implement int is_sorted(const int *a, size_t n).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Compare each element with its predecessor, starting at index 1.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
int is_sorted(const int *a, size_t n)
{
for(size_t i=1;i<n;++i)if(a[i]<a[i-1])return 0;
return 1;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
int is_sorted(const int *a, std::size_t n)
{
for(std::size_t i=1;i<n;++i)if(a[i]<a[i-1])return 0;
return 1;
}
A descending adjacent pair proves the array is not sorted. Starting at index 1 avoids reading a[-1].
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
int a[]={-1,2,2,9}, b[]={1,3,2};
CHECK(is_sorted(a,4)==1);
CHECK(is_sorted(b,3)==0);
CHECK(is_sorted(NULL,0)==1);
CHECK(is_sorted(b,1)==1);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}