Answer to Question #294767 in C++ for Nice

Question #294767

Sample Program Run:

Enter number of test cases: 3


Enter the size of the array: 5

Enter the elements of the array: 5 1 4 2 3

Number of Inversions: 6


Enter the size of the array: 10

Enter the elements of the array: 2 1 3 4 5 6 7 9 8 10

Number of Inversions: 2


Enter the size of the array: 7

Enter the elements of the array: 4 1 3 5 2 3 8

Number of Inversions: 7


1
Expert's answer
2022-02-07T05:10:29-0500
#include <iostream>
using namespace std;


int main() {
    int arr[100];
    int tests, n;


    cout << "Enter number of test cases: ";
    cin >> tests;
    cout << endl;


    for (int t=0; t<tests; t++) {
        cout << "Enter the size of the array: ";
        cin >> n;
        if (n > 100) {
            n = 100;
            cout << "The number was reduced to 100" << endl;
        }


        cout << "Enter the elements of the array: ";
        for (int i=0; i<n; i++) {
            cin >> arr[i];
        }


        int n_invers = 0;
        for (int i=0; i<n-1; i++) {
            for (int j=i+1; j<n; j++) {
                if (arr[i] > arr[j]) {
                    n_invers++;
                }
            }
        }


        cout << "Number of inversion: " << n_invers << endl << endl;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog