Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Count Inversions in an array
The inversions of an array indicate; how many changes are required to convert the array into its sorted form. When an array is already sorted, it needs 0 inversions, and in another case, the number of inversions will be maximum, if the array is reversed.
To solve this problem, we will follow the Merge sort approach to reduce the time complexity, and make it in Divide and Conquer algorithm.
Input and Output
Input: A sequence of numbers. (1, 5, 6, 4, 20). Output: The number of inversions required to arrange the numbers into ascending order. Here the number of inversions are 2. First inversion: (1, 5, 4, 6, 20) Second inversion: (1, 4, 5, 6, 20)
Algorithm
merge(array, tempArray, left, mid, right)
Input: Two arrays, who have merged, the left, right and the mid indexes.
Output: The merged array in sorted order.
Begin i := left, j := mid, k := right count := 0 while imergeSort(array, tempArray, left, right)
Input: Given an array and temporary array, left and right index of the array.
Output − Number of inversions after sorting.
Begin count := 0 if right > left, then mid := (right + left)/2 count := mergeSort(array, tempArray, left, mid) count := count + mergeSort(array, tempArray, mid+1, right) count := count + merge(array, tempArray, left, mid+1, right) return count EndExample
#includeusing namespace std; int merge(intarr[], int temp[], int left, int mid, int right) { int i, j, k; int count = 0; i = left; //i to locate first array location j = mid; //i to locate second array location k = left; //i to locate merged array location while ((i left) { mid = (right + left)/2; //find mid index of the array count = mergeSort(arr, temp, left, mid); //merge sort left sub array count += mergeSort(arr, temp, mid+1, right); //merge sort right sub array count += merge(arr, temp, left, mid+1, right); //merge two sub arrays } return count; } intarrInversion(intarr[], int n) { int temp[n]; return mergeSort(arr, temp, 0, n - 1); } int main() { intarr[] = {1, 5, 6, 4, 20}; int n = 5; cout Output
Number of inversions are 2
