Program to check if an array is sorted or not (Iterative and Recursive)
Last Updated :
17 Apr, 2024
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 an 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
Approach 1: Recursive approach
The basic idea for the 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++
// C++ Recursive approach to check if an
// Array is sorted or not
#include <iostream>
using namespace std;
// Function that returns true if array is
// sorted in non-decreasing order.
bool arraySortedOrNot(int a[], int n)
{
// Base case
if (n == 1 || n == 0)
{
return true;
}
// Check if present index and index
// previous to it are in correct order
// and rest of the array is also sorted
// if true then return true else return
// false
return a[n - 1] >= a[n - 2] &&
arraySortedOrNot(a, n - 1);
}
// Driver code
int main()
{
int arr[] = { 20, 23, 23, 45, 78, 88 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
if (arraySortedOrNot(arr, n))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
return 0;
}
// This code is contributed by avanitrachhadiya2155
C
// C Recursive approach to check if an
// Array is sorted or not
#include <stdio.h>
// Function that returns true if array is
// sorted in non-decreasing order.
int arraySortedOrNot(int a[], int n)
{
// Base case
if (n == 1 || n == 0) {
return 1;
}
// Check if present index and index
// previous to it are in correct order
// and rest of the array is also sorted
// if true then return true else return
// false
return a[n - 1] >= a[n - 2]
&& arraySortedOrNot(a, n - 1);
}
// Driver code
int main()
{
int arr[] = { 20, 23, 23, 45, 78, 88 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
if (arraySortedOrNot(arr, n)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
Java
// Java Recursive approach to check if an
// Array is sorted or not
class GFG {
// Function that returns true if array is
// sorted in non-decreasing order.
static boolean arraySortedOrNot(int a[], int n)
{
// base case
if (n == 1 || n == 0)
return true;
// check if present index and index
// previous to it are in correct order
// and rest of the array is also sorted
// if true then return true else return
// false
return a[n - 1] >= a[n - 2]
&& arraySortedOrNot(a, n - 1);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 20, 23, 23, 45, 78, 88 };
int n = arr.length;
// Function Call
if (arraySortedOrNot(arr, n))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Durgesh N. Birmiwal.
Python3
# Python3 recursive program to check
# if an Array is sorted or not
# Function that returns true if array
# is sorted in non-decreasing order.
def arraySortedOrNot(arr, n):
# Base case
if (n == 0 or n == 1):
return True
# Check if present index and index
# previous to it are in correct order
# and rest of the array is also sorted
# if true then return true else return
# false
return (arr[n - 1] >= arr[n - 2] and
arraySortedOrNot(arr, n - 1))
# Driver code
arr = [ 20, 23, 23, 45, 78, 88 ]
n = len(arr)
# Function Call
if (arraySortedOrNot(arr, n)):
print("Yes")
else:
print("No")
# This code is contributed by Virusbuddah
C#
// C# recursive approach to check if an
// Array is sorted or not
using System;
class GFG{
// Function that returns true if array is
// sorted in non-decreasing order.
static bool arraySortedOrNot(int[] a, int n)
{
// Base case
if (n == 1 || n == 0)
{
return true;
}
// Check if present index and index
// previous to it are in correct order
// and rest of the array is also sorted
// if true then return true else return
// false
return a[n - 1] >= a[n - 2] &&
arraySortedOrNot(a, n - 1);
}
// Driver code
static public void Main()
{
int[] arr = { 20, 23, 23, 45, 78, 88 };
int n = arr.Length;
// Function Call
if (arraySortedOrNot(arr, n))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
// This code is contributed by rag2127
Javascript
<script>
// JavaScript Recursive approach to check if an
// Array is sorted or not
// Function that returns true if array is
// sorted in non-decreasing order.
function arraySortedOrNot(a, n)
{
// Base case
if (n == 1 || n == 0)
{
return true;
}
// Check if present index and index
// previous to it are in correct order
// and rest of the array is also sorted
// if true then return true else return
// false
return a[n - 1] >= a[n - 2] &&
arraySortedOrNot(a, n - 1);
}
// Driver code
let arr = [ 20, 23, 23, 45, 78, 88 ];
let n = arr.length;
// Function Call
if (arraySortedOrNot(arr, n))
{
document.write("Yes" + "<br>");
}
else
{
document.write("No" + "<br>");
}
// This code is contributed by Surbhi Tyagi.
</script>
Time Complexity: O(n)
Auxiliary Space: O(n) for Recursion Call Stack.
Approach 2: Iterative approach
The idea is pretty much the same. The benefit of the iterative approach is it avoids the usage of recursion stack space and recursion overhead . Logic is to iterate over the whole array and in every iteration check whether arr[i] > arr[i-1] or not .
Below is the implementation using iteration:
C++
// C++ program 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";
}
C
// C program to check if an
// Array is sorted or not
#include <stdio.h>
// Function that returns true if array is
// sorted in non-decreasing order.
int arraySortedOrNot(int arr[], int n)
{
// Array has one or no element
if (n == 0 || n == 1)
return 1;
for (int i = 1; i < n; i++) {
// Unsorted pair found
if (arr[i - 1] > arr[i])
return 0;
}
// No unsorted pair found
return 1;
}
// Driver code
int main()
{
int arr[] = { 20, 23, 23, 45, 78, 88 };
int n = sizeof(arr) / sizeof(arr[0]);
if (arraySortedOrNot(arr, n))
printf("Yes\n");
else
printf("No\n");
return 0;
}
Java
// Recursive approach to check if an
// Array is sorted or not
class GFG {
// Function that returns true if array is
// sorted in non-decreasing order.
static boolean 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
public static void main(String[] args)
{
int arr[] = { 20, 23, 23, 45, 78, 88 };
int n = arr.length;
if (arraySortedOrNot(arr, n))
System.out.print("Yes\n");
else
System.out.print("No\n");
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to check if an
# Array is sorted or not
# Function that returns true if array is
# sorted in non-decreasing order.
def arraySortedOrNot(arr, n):
# Array has one or no element
if (n == 0 or n == 1):
return True
for i in range(1, n):
# Unsorted pair found
if (arr[i-1] > arr[i]):
return False
# No unsorted pair found
return True
# Driver code
arr = [20, 23, 23, 45, 78, 88]
n = len(arr)
if (arraySortedOrNot(arr, n)):
print("Yes")
else:
print("No")
# This code is contributed by Anant Agarwal.
C#
// Recursive approach to check if an
// Array is sorted or not
using System;
class GFG
{
// Function that returns true if array is
// sorted in non-decreasing order.
static 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
public static void Main(String[] args)
{
int []arr = { 20, 23, 23, 45, 78, 88 };
int n = arr.Length;
if (arraySortedOrNot(arr, n))
Console.Write("Yes\n");
else
Console.Write("No\n");
}
}
// This code is contributed by PrinciRaj1992
Javascript
<script>
// Javascript program Recursive approach to check if an
// Array is sorted or not
// Function that returns true if array is
// sorted in non-decreasing order.
function arraySortedOrNot(arr, n)
{
// Array has one or no element
if (n == 0 || n == 1)
return true;
for (let i = 1; i < n; i++)
// Unsorted pair found
if (arr[i - 1] > arr[i])
return false;
// No unsorted pair found
return true;
}
// Driver Code
let arr = [ 20, 23, 23, 45, 78, 88 ];
let n = arr.length;
if (arraySortedOrNot(arr, n))
document.write("Yes\n");
else
document.write("No\n");
// This code is contributed by sanjoy_62.
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 3 : Using two pointers
Here is a two pointer approach to check whether the given array is sorted or not . It works by taking two pointers left =0 and right = length -1 .
Every time we compare arr[left] and arr[right] , for ascending we check if arr[left] < arr[right] .
If the condition above is true then we compare the left and its previous , right and its next .
else we directly return false
Here is the code for the above approach :
C++
#include <iostream>
using namespace std;
bool isSorted(int arr[], int n) {
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] > arr[right]) {
return false;
} else {
if (left != 0 && right != n - 1 && (arr[left] < arr[left - 1] || arr[right] > arr[right + 1])) {
return false;
}
}
left++;
right--;
}
return true;
}
int main() {
int arr[] = {20, 20, 45, 89, 89, 90}; // Output: true
int nums[] = {20, 20, 78, 98, 99, 97}; // Output: false
cout << boolalpha << isSorted(arr, 6) << endl;
cout << boolalpha << isSorted(nums, 6) << endl;
return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
bool isSorted(int arr[], int n) {
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] > arr[right]) {
return false;
} else {
if (left != 0 && right != n - 1 && (arr[left] < arr[left - 1] || arr[right] > arr[right + 1])) {
return false;
}
}
left++;
right--;
}
return true;
}
int main() {
int arr[] = {20, 20, 45, 89, 89, 90}; // Output: true
int nums[] = {20, 20, 78, 98, 99, 97}; // Output: false
printf("%s\n", isSorted(arr, 6) ? "true" : "false");
printf("%s\n", isSorted(nums, 6) ? "true" : "false");
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static boolean isSorted(int arr[])
{
int left = 0, n = arr.length, right = n - 1;
while (left < right) {
if (arr[left] > arr[right]) {
return false;
}
else {
if (left != 0 && right != n - 1
&& (arr[left] < arr[left - 1]
|| arr[right] > arr[right + 1])) {
return false;
}
}
left++;
right--;
}
return true;
}
public static void main(String[] args)
{
int arr[]
= { 20, 20, 45, 89, 89, 90 }; /// Output : true;
int nums[]
= { 20, 20, 78, 98, 99, 97 }; // output False
System.out.println(isSorted(arr));
System.out.println(isSorted(nums));
}
}
Python
def is_sorted(arr):
left, right = 0, len(arr) - 1
while left < right:
if arr[left] > arr[right]:
return False
elif left != 0 and right != len(arr) - 1 and (arr[left] < arr[left - 1] or arr[right] > arr[right + 1]):
return False
left += 1
right -= 1
return True
arr = [20, 20, 45, 89, 89, 90] # Output: True
nums = [20, 20, 78, 98, 99, 97] # Output: False
print(is_sorted(arr))
print(is_sorted(nums))
JavaScript
function isSorted(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
if (arr[left] > arr[right]) {
return false;
} else {
if (left !== 0 && right !== arr.length - 1 && (arr[left] < arr[left - 1] || arr[right] > arr[right + 1])) {
return false;
}
}
left++;
right--;
}
return true;
}
let arr = [20, 20, 45, 89, 89, 90]; // Output: true
let nums = [20, 20, 78, 98, 99, 97]; // Output: false
console.log(isSorted(arr));
console.log(isSorted(nums));
Output :
True
False
Time complexity : O(n/2) which is O(n) linear time.
Space complexity : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...