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
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.

👉 For weekly algorithms practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels

advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations