Java Program to count inversions of size three in a given array


Inversion count is a step counting method by which we can calculate the number of sorting steps taken by a particular array. It is also capable to count the operation time span for an array. But, if we want to sort an array in a reverse manner, the count will be maximum number present in that array.

Array: { 5, 4, 3, 2, 1}  // for the reverse manner
Pairs: {5, 4}, {5,3} , {3,2}, {3,1}, {2,1},{4,3}, {4,2}, {4,1},}, {5,2}, {5,1}
Output: 10
Array: {1, 2, 3, 4, 5}  // for the increasing manner
Pairs: No Pairs
Output: 0
Array: {1,5,2,8,3,4}
Pairs: {5, 2}, {5, 3}, {5, 4}, {8, 3}, {8, 4}
Output: 5 

The inversion count indicates that how far that particular array is from being sorted in an increasing order. Here are two particular process to describe this situation attached with a solution −

  • To find the smaller elements − To find out the smaller element from an array, we need to iterate the index from n-1 to 0. By applying (a[i]-1), we can calculate the getSum() here. The process will run until it reach to a[i]-1.

  • To find the greater number − To find the greater number from an index we need to perform iteration 0 to n-1. For the every element we need to do calculation for every number till a[i]. Subtract it from i. Then we will get a the number which is greater than a[i].

Algorithm to count inversions of size three in an array:-

Here in this algorithm; we learn how to count inversions of size three in a given array in a particular programming environment.

  • Step 1 − Start

  • Step 2 − Declare an array and inversion count (As arr[] --> array and invCount --> Inversion count)

  • Step 3 − Inner loop y=x+1 to N

  • Step 4 − If element at x is greater than element at y index

  • Step 5 − Then, increase the invCount++

  • Step 6 − Print the pair

  • Step 7 − Terminate

Syntax to count inversions of size three in an array:-

A pair (A[i], A[j]) is said to be in inversion if: A[i] > A[j] and i < j

C++ Implementation

int getInversions(int * A, int n) {
  int count = 0;
  for (int i = 0; i < n; ++i) {
    for (int j = i + 1; j < n; ++j) {
      if (A[i] > a[j]) {
        ++count;
      }
    }
  }
  return count;
}

Java Implementation

public static int getInversions(int[] A, int n) {
  int count = 0;
 
  for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
      if (A[i] > A[j]) {
        count += 1;
      }
 
    }
  }
  return count;
}

Python Implementation

def getInversions(A, n):
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if A[i] > A[j]:
                count += 1
 
    return count;
}

Here we have mentioned the possible syntaxes to count inversions of size three in a given array. And for this method; Time Complexity is O(N^2), where N is the total size of the array and; Space Complexity:O(1), as no extra space has been used.

Approaches to follow

  • Approach 1 − Count Inversions of size three in a given array by program to count inversions of size 3

  • Approach 2 − Better Approach to count inversions of size 3

  • Approach 3 − Count inversions of size 3 using binary indexed tree

Count Inversions of size three in a given array by program to count inversions of size 3

For the simple approach to count inversions of size three, we need to run a loop for all possible value of i, j and k. The time complexity is O(n^3) and O(1) reflects the auxiliary space.

The condition is:

a[i] > a[j] > a[k] and i < j < k.

Example 1

public class Inversion{
	int getInvCount(int arr[], int n){
		int invcount = 0;
		
		for(int i=0 ; i< n-2; i++){
			for(int j=i+1; j<n-1; j++){
				if(arr[i] > arr[j]){
					for(int k=j+1; k<n; k++){
						if(arr[j] > arr[k])
							invcount++;
					}
				}
			}
		}
		return invcount;
	}
	public static void main(String args[]){
		Inversion inversion = new Inversion();
		int arr[] = new int[] {8, 4, 2, 1};
		int n = arr.length;
		System.out.print("Inversion count after method: " +
					inversion.getInvCount(arr, n));
	}
}

Output

Inversion count after method: 4

A better approach to count inversions of size 3

In this method we will consider the every element of an array as middle element of inversion. It helps to reduce the complexity. For this approach, the time complexity is O(n^2) and auxiliary Space is O(1).

Example 2

public class Inversion {
	int getInvCount(int arr[], int n){
		int invcount = 0; 
		
		for (int i=0 ; i< n-1; i++){
			int small=0;
			for (int j=i+1; j<n; j++)
				if (arr[i] > arr[j])
					small++;
			int great = 0;
			for (int j=i-1; j>=0; j--)
						if (arr[i] < arr[j])
							great++;
			invcount += great*small;
		}
		return invcount;
	}
	public static void main(String args[]){
		Inversion inversion = new Inversion();
		int arr[] = new int[] {8, 4, 2, 1};
		int n = arr.length;
		System.out.print("Inversion count afret the operation : " +
					inversion.getInvCount(arr, n));
	}
}

Output

Inversion count afret the operation : 4

Count inversions of size 3 using binary indexed tree

In this method, we count the greater elements and smaller ones too. Then perform the multiply operation greater[] to smaller[] and add it to the final result. Here the time complexity is O(n*log(n)) and auxiliary space denoted as O(n).

Example 3

import java.io.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.lang.*;
import java.util.Collections;

public class rudrabytp {
   static int N = 100005;
   static int BIT[][] = new int[4][N];
   static void updateBIT(int t, int i, int val, int n){
      while (i <= n) {
         BIT[t][i] = BIT[t][i] + val;
         i = i + (i & (-i));
      }
   }
   static int getSum(int t, int i){
      int res = 0;
      while (i > 0) {
         res = res + BIT[t][i];
         i = i - (i & (-i));
      }
      return res;
   }
   static void convert(int arr[], int n){
      int temp[]=new int[n];
      for (int i = 0; i < n; i++)
         temp[i] = arr[i];
      Arrays.sort(temp);
      for (int i = 0; i < n; i++) {
         arr[i] = Arrays.binarySearch(temp,arr[i]) + 1;
      }
   }
   public static int getInvCount(int arr[], int n){
      convert(arr, n);
      for (int i = n - 1; i >= 0; i--) {
         updateBIT(1, arr[i], 1, n);
         for (int l = 1; l < 3; l++) {
            updateBIT(l + 1, arr[i], getSum(l, arr[i] - 1), n);
         }
      }
      return getSum(3, n);
   }
   public static void main (String[] args){
      int arr[] = {8, 4, 2, 1};
      int n = arr.length;
      System.out.print("Inversion Count After The Operation : "+getInvCount(arr, n));
   }
}

Output

Inversion Count After The Operation : 4

Conclusion

In this article, we have learnt today how to count inversions of size three in a given array. Hope with this article and the mentioned codes using the particular language, you have got a broad view about this topic.

Updated on: 13-Apr-2023

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements