C++ Program to Count Inversions in an Array

This is a C++ program to count the inversion in an array.

Problem Description

1. The number of switches required to make an array sorted is termed as inversion count.
2. Its value varies with the sorting algorithms.
3. The time complexity is O(n^2).

Problem Solution

1. Compare the values of the element with each other.
2. Increment the counter if the value at lower index is higher.
3. Display the result.
4. Exit.

Program/Source Code

C++ program to count the inversion in an array.
This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on a Windows system.

#include<iostream>
 
using namespace std;
 
int CountInversion(int a[], int n)
{
	int i, j, count = 0;
	for(i = 0; i < n; i++)
	{
		for(j = i+1; j < n; j++)
			if(a[i] > a[j])
				count++;
	}
	return count;
}
 
int main()
{
	int n, i;
	cout<<"\nEnter the number of data element: ";
	cin>>n;
 
	int arr[n];
	for(i = 0; i < n; i++)
	{
		cout<<"Enter element "<<i+1<<": ";
		cin>>arr[i];
	}
 
	// Printing the number of  inversion in the array.
	cout<<"\nThe number of  inversion in the array: "<<CountInversion(arr, n);
 
	return 0;
}
Program Explanation

1. Take input of data.
2. Call CountInversion() function with ‘arr’ the array of data and ‘n’ the number of values, in the argument list.
3. Using nested loops compare all the element with each other.
4. Increment the counter if a[i] > a[j] where i < j. 5. Return to main and display the result. 6. Exit.

Runtime Test Cases
advertisement
advertisement
Case 1:
Enter the number of data element: 10
Enter element 1: 9
Enter element 2: 3
Enter element 3: 2
Enter element 4: 6
Enter element 5: 8
Enter element 6: 4
Enter element 7: 5
Enter element 8: 7
Enter element 9: 0
Enter element 10: 1
 
The number of  inversion in the array: 29

Sanfoundry Global Education & Learning Series – C++ Algorithms.
To practice all C++ Algorithms, here is complete set of 1000 C++ Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.