505,199 views
18 votes
18 votes
Write a recursive function that returns 1 if an array of size n is in sorted order and 0 otherwise. Note: If array a stores 3, 6, 7, 7, 12, then isSorted(a, 5) should return 1 . If array b stores 3, 4, 9, 8, then isSorted(b, 4) should return 0.

User Mir
by
2.9k points

1 Answer

19 votes
19 votes

Answer:

The function in C++ is as follows:

int isSorted(int ar[], int n){

if (
n == 1 ||
n == 0){

return 1;}

if (
ar[n - 1] <
ar[n - 2]){

return 0;}

return isSorted(ar, n - 1);}

Step-by-step explanation:

This defines the function

int isSorted(int ar[], int n){

This represents the base case; n = 1 or 0 will return 1 (i.e. the array is sorted)

if (
n == 1 ||
n == 0){

return 1;}

This checks if the current element is less than the previous array element; If yes, the array is not sorted

if (
ar[n - 1] <
ar[n - 2]){

return 0;}

This calls the function, recursively

return isSorted(ar, n - 1);

}

User DainDwarf
by
3.1k points