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:
#include <bits/stdc++.h>
using namespace std;
int arraySortedOrNot( int arr[], int n)
{
if (n == 1 || n == 0)
return 1;
if (arr[n - 1] < arr[n - 2])
return 0;
return arraySortedOrNot(arr, n - 1);
}
int main()
{
int arr[] = { 20, 23, 23, 45, 78, 88 };
int n = sizeof (arr) / sizeof (arr[0]);
if (arraySortedOrNot(arr, n))
cout << "Yes
" ;
else
cout << "No
" ;
}
|
/div>
Java
class CkeckSorted {
static int arraySortedOrNot( int arr[], int n)
{
if (n == 1 || n == 0 )
return 1 ;
if (arr[n - 1 ] < arr[n - 2 ])
return 0 ;
return arraySortedOrNot(arr, n - 1 );
}
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
def arraySortedOrNot(arr):
n = len (arr)
if n = = 1 or n = = 0 :
return True
return arr[ 0 ]< = arr[ 1 ] and arraySortedOrNot(arr[ 1 :])
arr = [ 20 , 23 , 23 , 45 , 78 , 88 ]
if arraySortedOrNot(arr): print ( "Yes" )
else : print ( "No" )
|
0
0
You Might Also Like
Subscribe to Our Newsletter
leave a comment
0 Comments