
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Count Inversion in an Array
The inverse count of an array indicates how far or how close the array is from being sorted. If the array is already sorted, then the inverse count is zero, but if the array is sorted in reverse order, then the inverse count is maximum.
Here we have given an integer array of size n and need to find the inversions in the array. If two array elements arr[i] and arr[j] form an inversion if arr[i]>arr[j] and i
Input / Output Scenario
Let's see the following input output scenario:
Input: arr[] = {6, 4, 2, 1} Output: 6

Input: arr[] = {1, 2, 3, 4} Output: 0
In the above scenario, there is no pair of indices (i, j) that exists in the given array such that arr[i]>arr[j] and i For each index in the array, we will count how many smaller elements are present on its right side. Then we will use a nested loop to calculate the inversion count and return the total. In the following example, we use the naive approach in C++ to count the inversions in the array - Following is the output of the above code - We can use merge sort to count the number of inversions in an array efficiently in O(n log n) time and O(n) space. First, we split the array into two halves: the left half and the right half. Then, we recursively count the number of inversions in each half. While merging the two halves back together, we also count the number of inversions that happen between the left and right halves (when an element from the left half is greater than one from the right half). Finally, we add up the inversions from the left, right, and between the halves to get the total number of inversions in the array. In the following example, we use the merge sort in C++ to count the inversions in the array - Following is the output of the code ?Count Inversion in an Array Using Naive Approach
Example
#include
6
Count Inversion in an Array Using Merge Sort
Example
#include
6