Count Inversions In An Array
Sorting an array seems like an easy process especially when the dataset is small. But what to do when the data is large or may contain 1000s of entries?
No matter which sorting algorithm you use, the time and space required in your system will increase.
However, to avoid this issue, an inversion count is done.
An inversion count simply determines how close your array is to being sorted. For instance, if you are asked to sort array of 0 1 2, the inversion count will determine how many times the elements will change their positions to give a sorted array.
After knowing that, you can apply the sorting algorithm which seems feasible. However, if the array is already sorted, inversion count will save all your effort to go through the process of sorting.
But how do you count inversions in an array?
To count inversions in an array, multiple approaches are followed. Here, we have discussed all the approaches in detail. So, keep reading!
Methods To Count Inversions In An Array
Method 1: The Basic Approach
This is the most basic approach to count inversions in an array. In this approach, you will have to traverse the complete array.
After that for each index, you will have to determine how many small elements are present on the right of the given array. This approach uses a nested loop to count inversions. It then calculates the total number of indexes in the array and then prints their sum.
Algorithm Of This Approach:
- From the beginning to the ending, first, traverse the array.
- Now, for each element, you will have to find the number of elements which are smaller than the present number. For this, you will have to use another loop.
- You will then have to calculate the sum of all the inversions at every index.
- In the end, print the sum of all the inversions.
Complexity Analysis Of This Approach:
- Space Complexity: The space complexity of the basic approach is O(1) because there is no additional space required.
- Time Complexity: The time complexity of this approach is O(n^2) because of the nested loops used to traverse the given array.
Method 2: Merge Sort
The basic approach to count inversions takes a lot more time to completely traverse the array. Therefore, enhanced merge sort is used to count inversions in an array.
This approach follows a divide and conquers approach to count the total number of inversions in an array. To begin with, it first divides the array into two parts and then counts inversions on both sides. After this, these halves are merged together and the sum of inversions on both halves is calculated to find the total inversion count.
The approach utilizes two pointers to traverse the equal halves of the array simultaneously. However, there are chances that while merging, there are some inversions left and may not be counted.
To solve this issue, inversions on the left side, merge() and right side of the array needs to be calculated.
Comments
Post a Comment