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

Related Posts:

  1. Program to print Alternate Elements of an Array.
  2. Program to swap kth element from beginning to kth element from end in an Array.
  3. Program to print all possible subarrays of the given array.
  4. Program to print kth smallest and kth largest element of an Array.
  5. Program to find equilibrium index of an Array.
  6. Program to find majority element of an Array.
  7. Program to find mean of the Array.
  8. Program to sort an Array of 0s and 1s.
  9. Program to Reverse an Array.
  10. Program to count number of odd numbers and even numbers in an array.
  11. Program to find absolute difference between sum of odd index elements and even index elements.
  12. Program to find smallest and largest element of the array.
  13. Program to count occurrences of a particular element in an array.
  14. Program to search an element in an Array (Linear Search).
  15. Program to Rotate Array Elements by ‘D’ positions.
  16. Program to find most frequent element in an array.
  17. Program to find pair in an array with given sum.
  18. Program to find first repeating element of an array.
  19. Program to merge two sorted arrays.
  20. Program to find missing number in an array.

You may also like...

Leave a Reply

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