You are here

C program to check if an array is sorted or not (ascending or descending or none)

C program to check if an array is sorted or not, i.e., in ascending order or descending order. Variables "a" and "d" in the program are for ascending and descending respectively and are initialized to one. If anyone of its element is greater than the next one, then it isn't in ascending order (a = 0). If anyone of its element is less than the next one, then it isn't in descending order (d = 0). We check the conditions for all consecutive elements of the array. If both the conditions are TRUE, then it isn't sorted. If anyone of them is FALSE, then it's sorted.

Is an array in ascending order or descending order?

#include <stdio.h>

int main()
{
  int n, s[1000], a = 1, d = 1, i;

  scanf("%d", &n);

  for (i = 0; i < n; i++)
    scanf("%d", &s[i]);

  i = 0;

  while ((a == 1 || d == 1) && i < n - 1) {
    if (s[i] < s[i+1])
      d = 0;
    else if (s[i] > s[i+1])
      a = 0;
    i++;
  }

  if (a == 1)
    printf("The array is sorted in ascending order.\n");
  else if (d == 1)
    printf("The array is sorted in descending order.\n");
  else
    printf("The array is not sorted.\n");

  return 0;
}

Check array sorted or not using a function

#include <stdio.h>

int isArraySorted(int [], int);

int main()
{
  int n, s[1000], i, r;

  scanf("%d", &n);

  for (i = 0; i < n; i++)
    scanf("%d", &s[i]);

  r = isArraySorted(s, n);

  if (r == 1)
    printf("The array is sorted in ascending order.\n");
  else if (r == 2)
    printf("The array is sorted in descending order.\n");
  else
    printf("The array isn't sorted.\n");

  return 0;
}

int isArraySorted(int s[], int n) {
  int a = 1, d = 1, i = 0;

  while ((a == 1 || d == 1) && i < n - 1) {
    if (s[i] < s[i+1])
      d = 0;
    else if (s[i] > s[i+1])
      a = 0;
    i++;
  }

  if (a == 1)
    return 1;
  else if (d == 1)
    return 2;
  else
    return 0;
}

Share this