Program to check if an array is sorted or not (Iterative and Recursive)

2.5

Given an array of size n, write a program to check if it is sorted in ascending order or not. Equal values are allowed in array and two consecutive equal values are considered sorted.

Examples:

Input : 20 21 45 89 89 90
Output : Yes

Input : 20 20 45 89 89 90
Output : Yes

Input : 20 20 78 98 99 97
Output : No

Recursive approach:

The basic idea for recursive approach:

1: If size of array is zero or one, return true.
2: Check last two elements of array, if they are
   sorted, perform a recursive call with n-1
   else, return false.
If all the elements will be found sorted, n will
eventually fall to one, satisfying Step 1.

Below is the implementation using recursion:

C++

// Recursive approach to check if an
// Array is sorted or not
#include<bits/stdc++.h>
using namespace std;

// Function that returns 0 if a pair
// is found unsorted
int arraySortedOrNot(int arr[], int n)
{
    // Array has one or no element or the
    // rest are already checked and approved.
    if (n == 1 || n == 0)
        return 1;

    // Unsorted pair found (Equal values allowed)
    if (arr[n-1] < arr[n-2])
        return 0;

    // Last pair was sorted
    // Keep on checking
    return arraySortedOrNot(arr, n-1);
}

// Driver code
int main()
{
    int arr[] = {20, 23, 23, 45, 78, 88};
    int n = sizeof(arr)/sizeof(arr[0]);
    if (arraySortedOrNot(arr, n))
        cout << "Yes\n";
    else
        cout << "No\n";
}

Java

// Recursive approach to check if an
// Array is sorted or not

class CkeckSorted
{
    // Function that returns 0 if a pair
    // is found unsorted
    static int arraySortedOrNot(int arr[], int n)
    {
        // Array has one or no element or the
        // rest are already checked and approved.
        if (n == 1 || n == 0)
            return 1;
     
        // Unsorted pair found (Equal values allowed)
        if (arr[n-1] < arr[n-2])
            return 0;
     
        // Last pair was sorted
        // Keep on checking
        return arraySortedOrNot(arr, n-1);
    }
    
    // main function
    public static void main (String[] args) 
    {
        int arr[] = {20, 23, 23, 45, 78, 88};
        int n = arr.length;
        if (arraySortedOrNot(arr, n)!=0)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

Python3

# Recursive approach to check if an
# Array is sorted or not

# Function that returns 0 if a pair
# is found unsorted
def arraySortedOrNot(arr):
    
    # Calculating length
    n = len(arr)
    
    # Array has one or no element or the
    # rest are already checked and approved.
    if n == 1 or n == 0:
        return True
        
    # Recursion applied till last element
    return arr[0]<=arr[1] and arraySortedOrNot(arr[1:])


arr = [20, 23, 23, 45, 78, 88]

# Displaying result
if arraySortedOrNot(arr): print("Yes")
else: print("No") 


Output:

Yes

Time Complexity : O(n)
Auxiliary Space : O(n) for Recursion Call Stack.

Iterative approach:
The idea is pretty much the same. The benefit of iterative approach is it avoids the usage of recursion stack space and recursion overhead.

Below is the c++ implementation using iteration:

// Recursive approach to check if an
// Array is sorted or not
#include<bits/stdc++.h>
using namespace std;

// Function that returns true if array is
// sorted in non-decreasing order.
bool arraySortedOrNot(int arr[], int n)
{
    // Array has one or no element
    if (n == 0 || n == 1)
        return true;

    for (int i = 1; i < n; i++)

        // Unsorted pair found
        if (arr[i-1] > arr[i])
            return false;

    // No unsorted pair found
    return true;
}

// Driver code
int main()
{
    int arr[] = {20, 23, 23, 45, 78, 88};
    int n = sizeof(arr)/sizeof(arr[0]);
    if (arraySortedOrNot(arr, n))
        cout << "Yes\n";
    else
        cout << "No\n";
}

Output:

Yes

Time Complexity : O(n)
Auxiliary Space : O(1)

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.5 Average Difficulty : 2.5/5.0
Based on 13 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.