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
#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;
}
}
Comments
Leave a comment