SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Arrays
Exercise:
Self-test Exercises
Question:16 | ISBN:9780321531346 | Edition: 7

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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.

 

 

0 0

Discussions

Post the discussion to improve the above solution.