Write a function named out_of_order that takes as parameters an array of doubles and an int parameter named size and returns a value of type int. This function will test this array for being out of order, meaning that the array violates the following condition:
a[0] <= a[1] <= a[2] <= ...
The function returns -1 if the elements are not out of order; otherwise, it will return the index of the first element of the array that is out of order.
For example, consider the declaration
double a[10] = {1.2, 2.1, 3.3, 2.5, 4.5,7.9, 5.4, 8.7, 9.9, 1.0};
In this array, a[2] and a[3] are the first pair out of order, and a[3] is the first element out of order, so the function returns 3. If the array were
sorted, the function would return –1.
PROGRAM CODE:
#include <iostream>
using namespace std;
int out_of_order(double a[], int size) {
for (int index = 0; index < size - 1; index++) {
if (a[index] > a[index + 1]) {
return index; // Return the index of the first out-of-order element
}
}
return -1; // Array is sorted
}
int main() {
double a[10] = {1.2, 2.1, 3.3, 2.5, 4.5, 7.9, 5.4, 8.7, 9.9, 1.0};
int size = sizeof(a) / sizeof(a[0]);
int result = out_of_order(a, size);
if (result == -1) {
cout << "Array is sorted." << endl;
} else {
cout << "Array elements " << result << " and " << (result + 1) << " are out of order." << endl;
}
return 0;
}
OUTPUT OF THE PROGRAM CODE:
Array elements 2 and 3 are out of order.