Print Inversions in an array in C

Print Inversions in an array in C

Problem statement: Print Inversions in an array. In an array two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
For example
Input: arr[] = {9, 5, 2, 1}
Output:
(9, 5), (5, 2), (9, 2), (9, 1), (5, 1), (2, 1)
Inversion count is 6
Naive Approach

//C program to print Inversions in an Array
#include <stdio.h>
#include <stdlib.h>
int getInversionCount(int arr[], int n)
{
	int count = 0;
	for (int i = 0; i < n - 1; i++)
		for (int j = i + 1; j < n; j++)
			if (arr[i] > arr[j]){
				count++;
				printf("{%d , %d}\n",arr[i],arr[j]);
				
				}

	return count;
}


int main()
{
	int arr[] = {9, 5, 2, 1};
	int n = sizeof(arr) / sizeof(arr[0]);
	printf("Inversion count is %d \n",getInversionCount(arr, n));
	return 0;
}
$ gcc arrInv.c
$ ./a.out
{9 , 5}
{9 , 2}
{9 , 1}
{5 , 2}
{5 , 1}
{2 , 1}
Inversion count is 6
$

also see

C Programming language
Go Programming language
Linked List Array
Simplification Queue
DBMS Reasoning
Aptitude HTML
Previous articleFirst C Program
Next articleCount the triplets in C

LEAVE A REPLY

Please enter your comment!
Please enter your name here