200k views
2 votes
Write the following function recursively. Note, a non-recursive solution to the following problem will result in a grade of 0, even if it is correct.

bool isSorted(int array[], int size);
This function is passed and array of integers and its size. Function returns true if the values are ordered from biggest to smallest, false otherwise.
For example:
array = {5, 3, 1 , -5, -10} --> return true
array = {1, 2, 3, 6, 7 } --> returns false
array = {10, 8 , 6, 5, 9} --> returns false

1 Answer

2 votes

Answer:

Step-by-step explanation:

Here's a possible recursive implementation of the isSorted function in C++:

```

bool isSorted(int array[], int size) {

if (size <= 1) {

return true;

} else {

return (array[size - 1] < array[size - 2]) ? false : isSorted(array, size - 1);

}

}

```

The function checks if the array is sorted recursively by comparing the last two elements of the array. If they are in the correct order, it calls itself with the size of the array decreased by 1. If they are not in the correct order, it returns false. If the size of the array is 1 or less, it returns true, since an array of 1 or 0 elements is always sorted.

User Ron Wertlen
by
8.6k points