Given the following examples: arr[] = {-3, -2, -1, 0, 1, 2} → Ascending order arr[] = {2, 1, 0, -1, -2, -3} → Descending order arr[] = {2, 1, -3, 0…

Given the following examples:

  • arr[] = {-3, -2, -1, 0, 1, 2} → Ascending order
  • arr[] = {2, 1, 0, -1, -2, -3} → Descending order
  • arr[] = {2, 1, -3, 0, -2, -1} → Unordered

Write a program in C, C++, or Java that takes an array of integers as input and determines whether the array is sorted in ascending order, descending order, or is unordered.

From the BUET MSC (CSE) October 2026 – Written exam, question 4 of 14.

Answers (1)

One pass: the array is ascending if no element is smaller than the one before it, descending if none is larger; otherwise unordered. O(n) time, O(1) extra space.

#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);
    int a[n];
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);

    int ascending = 1, descending = 1;
    for (int i = 1; i < n; i++) {
        if (a[i] < a[i - 1]) ascending = 0;
        if (a[i] > a[i - 1]) descending = 0;
    }

    if (ascending)       printf("Ascending order\n");
    else if (descending) printf("Descending order\n");
    else                 printf("Unordered\n");
    return 0;
}

{-3, -2, -1, 0, 1, 2} → Ascending; {2, 1, 0, -1, -2, -3} → Descending; {2, 1, -3, 0, -2, -1} → Unordered (it falls, then rises at -3 → 0).

— rhs

More from this paper