Write a C Program to Check if Array is Sorted

Write a C Program to Check if Array is Sorted

This question has been asked in many of the placement interviews. We can check an array is sorted or not by simply comparing all the elements with its next element.

There are two cases as per comparison between the element and its next element.

Case 1:

For all elements, if the element is equal to or less than its next element; we can conclude that the array is sorted in ascending order.

Case 2:

If it does not satisfy even for the single element, the array is not in ascending order.

This is one of the very important data structure interview coding questions.

Difficulty Level: Low

C Program to Check if Array is Sorted

Go through the following code to check array is sorted or not in ascending order.

#include<stdio.h>
#define nSize 10 //size of array
int main()
{
    int nArr[nSize]={0};
    int i=0;
    printf("Enter 10 Elements");
    for (i=0; i<10; i++)
        scanf("%d", &nArr[i]);
 
    for(i=0; i<nSize-1 ; i++) { if(nArr[i]>nArr[i+1])
        //if(nArr[i]<nArr[i+1]) to check descending order
        {
            printf("Array is not sorted in assenting order");
            return;
        }
    }
    printf("Array is sorted in assenting order");
}

Output :

Case 1:

input : 10 12 24 35 56 66 77 78 89 90
Output : Array is sorted in ascending order

Case 2:

input : 10 12 5 35 7 66 77 78 89 90
Output : Array is not sorted in ascending order

Note: To check the array is sorted or not in descending order, just use condition if(nArr[i]<nArr[i+1]) in the above code.

Time complexity:

As we are comparing each element at once with its next element, the time complexity is O(n).

You can also sort the given array. And then compare the original array with the output array.

If the elements in both arrays are the same and in the same order, the given array is sorted.

You can use any sorting algorithm to sort the given array. Like…

Do you know any other C program to check if array is sorted? Please share it in the comment?

2 Comments

    1. I guess you have confusion with nSize-1 and why it is not nSize. In our logic, every time in the loop, we are comparing the current element with the next element. We only have to traverse up to the second last element where the second last element will be compared with the last element. I hope it is clear.

Leave a Reply

Your email address will not be published. Required fields are marked *