Check if an Array is Sorted
Given an array arr[], 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: arr[] = [10, 20, 30, 40, 50]
Output: true
Explanation: The given array is sorted.Input: arr[] = [90, 80, 100, 70, 40, 30]
Output: false
Explanation: The given array is not sorted.
Table of Content
[Approach 1] Recursive approach - O(n) Time and O(n) Space
The idea behind recursive approach is check if the first two elements are in order, then recursively check the rest of the array. The base case is when the array has zero or one element, which is always considered sorted.
Step-By-Step Approach:
- If size of array is zero or one, return true.
- Check last two elements of array, if they are sorted, perform a recursive call with n-1 else, return false.
#include <iostream>
#include <vector>
using namespace std;
// Helper function that takes array and size, used for recursion
bool isSortedHelper(vector<int>& arr, int n) {
if (n == 0 || n == 1)
return true;
return arr[n - 1] >= arr[n - 2] && isSortedHelper(arr, n - 1);
}
// Main function to check if array is sorted, only takes array as input
bool isSorted(vector<int>& arr) {
return isSortedHelper(arr, arr.size());
}
int main() {
vector<int> arr = { 10, 20, 30, 40, 50 };
cout << (isSorted(arr) ? "true\n" : "false\n");
return 0;
}
class GFG {
static boolean isSortedHelper(int arr[], int n){
// Base Case
if (n == 1 || n == 0)
return true;
// Check if current and previous elements are in order
// and recursively check the rest of the array
return arr[n - 1] >= arr[n - 2] && isSortedHelper(arr, n - 1);
}
static boolean isSorted(int arr[]) {
return isSortedHelper(arr, arr.length);
}
public static void main(String[] args) {
int arr[] = { 10, 20, 30, 40, 50 };
int n = arr.length;
if (isSorted(arr))
System.out.print("true");
else
System.out.print("false");
}
}
def isSortedhelper(arr, n):
# Base case
if (n == 0 or n == 1):
return True
# Check if current and previous elements are in order
# and recursively check the rest of the array
return (arr[n - 1] >= arr[n - 2] and isSortedhelper(arr, n - 1))
def isSorted(arr):
n = len(arr)
return isSortedhelper(arr, n)
if __name__ == "__main__":
arr = [ 10, 20, 30, 40, 50 ]
if (isSorted(arr)):
print("true")
else:
print("false")
using System;
class GFG {
static bool isSortedhelper(int[] arr, int n){
// Base case
if (n == 1 || n == 0) {
return true;
}
// Check if current and previous elements are in
// order and recursively check the rest of the array
return arr[n - 1] >= arr[n - 2]
&& isSortedhelper(arr, n - 1);
}
static bool isSorted(int[] arr){
return isSortedhelper(arr, arr.Length);
}
static public void Main(){
int[] arr = { 10, 20, 30, 40, 50 };
// Function Call
if (isSorted(arr)) {
Console.WriteLine("true");
}
else {
Console.WriteLine("false");
}
}
}
function isSortedhelper(arr, n) {
// Base case
if (n == 1 || n == 0) {
return true;
}
// Check if current and previous elements are in order
// and recursively check the rest of the array
return arr[n - 1] >= arr[n - 2] && isSortedhelper(arr, n - 1);
}
function isSorted(arr){
let n = arr.length;
return isSortedhelper(arr, n);
}
// Driver Code
let arr = [10, 20, 30, 40, 50];
let n = arr.length;
if (isSorted(arr)) {
console.log("true");
}
else {
console.log("false");
}
Output
true
[Approach 2] Iterative approach - O(n) Time and O(1) Space
The idea is simple. We start traversing from the second element. For every element we check if it is smaller than or equal to previous element or not. At any point if we find previous element greater, we return false.
For example: arr[] = [10, 20, 30, 5, 6]
i = 1 : (10 <= 20), continue
i = 2 : (20 <= 30), continue
i = 3 : (30 > 5), return false.
#include <iostream>
#include <vector>
using namespace std;
bool isSorted(vector<int>& arr) {
// Iterate over the array and check if
// every element is greater than or
// equal to previous element.
for (int i = 1; i < arr.size(); i++)
if (arr[i - 1] > arr[i])
return false;
return true;
}
int main() {
vector<int> arr = { 10, 20, 30, 40, 50 };
cout << (isSorted(arr) ? "true\n" : "false\n");
return 0;
}
#include <stdio.h>
#include <stdbool.h>
bool isSorted(int arr[], int n) {
// Iterate over the array and check if
// every element is greater than or
// equal to previous element.
for (int i = 1; i < n; i++) {
if (arr[i - 1] > arr[i])
return false;
}
return true;
}
int main() {
int arr[] = { 10, 20, 30, 40, 50 };
int n = sizeof(arr) / sizeof(arr[0]);
if (isSorted(arr, n))
printf("true\n");
else
printf("false\n");
return 0;
}
class GFG {
static boolean isSorted(int arr[]) {
int n = arr.length;
// Iterate over the array and check if
// every element is greater than or
// equal to previous element.
for (int i = 1; i < n; i++)
if (arr[i - 1] > arr[i])
return false;
return true;
}
public static void main(String[] args) {
int arr[] = { 10, 20, 30, 40, 50 };
int n = arr.length;
if (isSorted(arr))
System.out.print("true\n");
else
System.out.print("false\n");
}
}
def isSorted(arr):
n = len(arr)
# Iterate over the array and check if
# every element is greater than or
# equal to previous element.
for i in range(1, n):
if (arr[i-1] > arr[i]):
return False
return True
if __name__ == "__main__":
arr = [10, 20, 30, 40, 50]
n = len(arr)
if (isSorted(arr)):
print("true")
else:
print("false")
using System;
class GFG {
static bool isSorted(int []arr) {
int n = arr.Length;
// Iterate over the array and check if
// every element is greater than or
// equal to previous element.
for (int i = 1; i < n; i++)
if (arr[i - 1] > arr[i])
return false;
return true;
}
public static void Main(String[] args) {
int []arr = { 10, 20, 30, 40, 50 };
int n = arr.Length;
if (isSorted(arr))
Console.Write("true\n");
else
Console.Write("false\n");
}
}
function isSorted(arr){
let n = arr.length;
// Iterate over the array and check if
// every element is greater than or
// equal to previous element.
for (let i = 1; i < n; i++) {
if (arr[i - 1] > arr[i]) {
return false;
}
}
return true;
}
// Driver Code
let arr = [10, 20, 30, 40, 50];
let n = arr.length;
if (isSorted(arr)) {
console.log("true");
} else {
console.log("false");
}
Output
true
[Approach 2] Using Built-in Methods (Applicable for C++ and Python Only) - O(n) Time and O(1) Space
The idea behind here is we use built-in methods in STL of C++ and Python to check if an array is sorted or not.
Note :
1. is_sorted() : The time complexity of using this C++ method is O(n) and consumes space with complexity of O(1).
2. sorted() : The time complexity of using this C++ method is O(nlogn) as Python uses Timsort (hybrid of merge/insertion sort). and consumes space with complexity of O(1).
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool isSorted(vector<int> &arr){
// is_sorted() is a built-in method
if(is_sorted(arr.begin(), arr.end()))
return true;
return false;
}
int main() {
vector<int> arr = { 10, 20, 30, 40, 50 };
if(isSorted(arr))
cout<<"true"<<endl;
else
cout<<"false"<<endl;
return 0;
}
def is_sorted(arr):
# sorted() is a built-in method for python
return arr == sorted(arr)
if __name__ == "__main__":
arr = [10, 20, 30, 40, 50]
if is_sorted(arr):
print("true")
else:
print("false")
Output
true