Check if Array is Sorted or Not

ā€œCheck if Array is Sorted or Notā€ is a basic problem of array data structure. Here, we are given an array of size ā€˜nā€™ and our task is to check if array is sorted or not.

Example:

INPUT:
Arr[9] = {11, 22, 33, 44, 55, 66, 77, 88, 99}
OUTPUT:
Array is sorted.
INPUT:
Arr[9] = {11, 33, 55, 77, 99, 22, 44, 66, 88}
OUTPUT:
Array is not sorted.

The steps required to check if array is sorted or not are as follows:

  1. Scan array size and array elements.
  2. Iterate over all the elements of array and check if every subsequent element is greater than or equal to current element or not. If yes, then array is sorted else array is not sorted.

C++ Program to check if array is sorted or not is as follows:

/* Program to check if array is sorted or not */  
#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    /* Scan size of array */  
    int n;  
    cout<<"Enter the size of an array: ";  
    cin>>n;  
      
    /* Scan Array Elements */  
    int arr[n];  
    cout<<"\nEnter array elements:\n";  
    for(int i = 0; i < n; i++)  
    {  
        cin>>arr[i];  
    }  
      
    int temp = 0;  
    for(int i = 1; i < n; i++)  
    {  
        /* If array is not sorted */  
        if(arr[i] < arr[i-1])  
        {  
            temp = 1;  
            break;  
        }  
    }  
      
    if(temp == 1)  
    cout<<"\nArray is not sorted!!";  
    else  
    cout<<"\nArray is sorted!!";  
      
}  

OUTPUT:
Enter the size of an array: 5
Enter array elements:
11 22 33 44 55
Array is sorted!!
Time Complexity:
O(n), where n is the length of array

You may also like...

Leave a Reply

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