14
5/12/12 Count Inversions in an array | GeeksforGeeks 1/14 www.geeksforgeeks.org/archives/3968 GeeksforGeeks A computer science portal for geeks Home Q&A Interview Corner Ask a question Feedback Contribute About us Subscribe Arrays Articles Bit Magic C/C++ Puzzles GFacts Linked Lists MCQ Misc Output Strings Trees Count Inversions in an array January 5, 2010 Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3). METHOD 1 (Simple) For each element, count number of elements which are on right side of it and are smaller than it.

Count Inversions in an Array _ GeeksforGeeks

Embed Size (px)

Citation preview

Page 1: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

1/14www.geeksforgeeks.org/archives/3968

GeeksforGeeks

A computer science portal for geeks

HomeQ&AInterview CornerAsk a question

FeedbackContributeAbout us

SubscribeArraysArticlesBit MagicC/C++ PuzzlesGFactsLinked ListsMCQMiscOutputStringsTrees

Count Inversions in an array

January 5, 2010

Inversion Count for an array indicates – how far (or close) the array is from being sorted. Ifarray is already sorted then inversion count is 0. If array is sorted in reverse order thatinversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j

Example:The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).

METHOD 1 (Simple)For each element, count number of elements which are on right side of it and are smaller thanit.

Page 2: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

2/14www.geeksforgeeks.org/archives/3968

Time Complexity: O(n^2)

METHOD 2(Enhance Merge Sort)Suppose we know the number of inversions in the left half and right half of the array (let beinv1 and inv2), what kinds of inversions are not accounted for in Inv1 + Inv2? The answer is– the inversions we have to count during the merge step. Therefore, to get number ofinversions, we need to add number of inversions in left subarray, right subarray and merge().

How to get number of inversions in merge()?

int getInvCount(int arr[], int n){ int inv_count = 0; int i, j; for(i = 0; i < n - 1; i++) for(j = i+1; j < n; j++) if(arr[i] > arr[j]) inv_count++; return inv_count;} /* Driver progra to test above functions */int main(int argv, char** args){ int arr[] = {1, 20, 6, 4, 5}; printf(" Number of inversions are %d \n", getInvCount(arr, 5)); getchar(); return 0;}

Page 3: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

3/14www.geeksforgeeks.org/archives/3968

In merge process, let i is used for indexing left sub-array and j for right sub-array. At any stepin merge(), if a[i] is greater than a[j], then there are (mid – i) inversions. because left and rightsubarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] … a[mid])will be greater than a[j]

The complete picture:

Implementation:

Page 4: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

4/14www.geeksforgeeks.org/archives/3968

#include <stdio.h>#include <stdlib.h> int _mergeSort(int arr[], int temp[], int left, int right);int merge(int arr[], int temp[], int left, int mid, int right); /* This function sorts the input array and returns the number of inversions in the array */int mergeSort(int arr[], int array_size){ int *temp = (int *)malloc(sizeof(int)*array_size); return _mergeSort(arr, temp, 0, array_size - 1);} /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */int _mergeSort(int arr[], int temp[], int left, int right){ int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left)/2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid+1, right); } return inv_count;} /* This funt merges two sorted arrays and returns inversion count in the arrays.*/int merge(int arr[], int temp[], int left, int mid, int right){ int i, j, k; int inv_count = 0; i = left; /* i is index for left subarray*/ j = mid; /* i is index for right subarray*/ k = left; /* i is index for resultant merged subarray*/ while ((i <= mid - 1) && (j <= right)) {

Page 5: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

5/14www.geeksforgeeks.org/archives/3968

Note that above code modifies (or sorts) the input array. If we want to count only inversionsthen we need to create a copy of original array and call mergeSort() on copy.

Time Complexity: O(nlogn)Algorithmic Paradigm: Divide and Conquer

if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; /*this is tricky -- see above explanation/diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count;} /* Driver progra to test above functions */int main(int argv, char** args){ int arr[] = {1, 20, 6, 4, 5}; printf(" Number of inversions are %d \n", mergeSort(arr, 5)); getchar(); return 0;}

Page 6: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

6/14www.geeksforgeeks.org/archives/3968

References:http://www.cs.umd.edu/class/fall2009/cmsc451/lectures/Lec08-inversions.pdfhttp://www.cp.eng.chula.ac.th/~piak/teaching/algo/algo2008/count-inv.htm

Please write comments if you find any bug in the above program/algorithm or other ways tosolve the same problem.

You may also like following posts

1. Merge an array of size n into another array of size m+n2. Given an array A[] and a number x, check for pair in A[] with sum as x3. Program for array rotation4. Write a program to reverse an array5. Reversal algorithm for array rotation

11 comments so far

1. Venkatesh says:January 19, 2012 at 7:18 AM

If we use modified insertion sort alg, we see best running time. for partially sorted arrayinsertion sort runs in linear time.

int arr[], array_size, inv_count;

for (int i = 0; i 0; j--)if (a[j] < a[j-1]))inv_count ++;elsebreak;

Reply2. jordi says:

March 1, 2011 at 1:28 AM

theres a linear solution that im looking for..

Reply

Send 8people

Page 7: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

7/14www.geeksforgeeks.org/archives/3968

Algoseekar says:April 24, 2011 at 4:59 PM

@jordi..i dont think we can do it linearly..??

Reply3. amit says:

November 30, 2010 at 9:32 AM

nice question !

Reply4. Naman Goel says:

November 16, 2010 at 11:14 AM

We can also use binary search tree method for thishere is the code-

#include<iostream>using namespace std; struct node{ int data; node *left; node *right; int rc;}; node *root = NULL; int get_inv(int val){ node *newnode = new node; newnode -> data = val; newnode -> left = NULL; newnode -> right = NULL; newnode -> rc = 0; int inv = 0; if(!root) { root = newnode; return 0; } node *ptr = root;

Page 8: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

8/14www.geeksforgeeks.org/archives/3968

ReplyJ says:

node *pptr = root; while(ptr) { pptr = ptr; if(val < ptr->data) { inv += ptr->rc +1; ptr = ptr->left; } else { ptr->rc++; ptr = ptr->right; } } if(val < pptr->data) { pptr->left = newnode; } else { pptr->right = newnode; } return inv;} int count_inv(int *array,int n){ int inv = 0; for(int i=0;i<n;i++) { inv += get_inv(array[i]); } return inv;} int main(){ int array[] = {3,6,1,2,4,5}; cout<<count_inv(array,6)<<endl; return 0;}

Page 9: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

9/14www.geeksforgeeks.org/archives/3968

January 15, 2011 at 9:43 PM

Really cool coding. I must learn to code like this.

ReplyJ says:January 15, 2011 at 9:57 PM

Memory is leaked in the above program. You cannot just call new and leave italone.

Replylaxman says:March 27, 2011 at 2:45 PM

@nama goel ..hi naman can you explain the algorithm..its awesome program.please write the algo.

Thankslaxman

ReplyVenki says:March 30, 2011 at 10:36 AM

If I understand the logic correctly, we are constructing BST from the arrayelements and maintaining a count on each node. The idea here is every parentnode must maintain the number of nodes that branched on to it's right side (rightcount). The above code fails if there are equal element which cause the count tobe incremented. Equal nodes won't participate in inversions. The count (rc) willbe used to track the number of inversions.

However, when the array is reverse sorted, the tree will be fully right skewed.While inserting i-th node, we need to visit previous (i-1) nodes, so the worst casecomplexity is no better than O(n^2).

Where as merge sort procedure doesn't depend on data to be sorted. What evermay be the permutation of input data, merge sort will sort the array in O(NlogN)time, so the inversion count.

Let me know if I am missing something to understand.

ReplyDecoder says:April 4, 2012 at 3:41 AM

Page 10: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

10/14www.geeksforgeeks.org/archives/3968

What if we insert equal element to right child of equal element, In this casecount won't be incremented.

ReplyDecoder says:April 4, 2012 at 3:44 AM

What if we insert equal element to right child of equal element, In this casecount won't be incremented.

Reply

Comment

Name (Required) Email (Required)

Website URI Your Comment (Writing code? please paste your

code between sourcecode tags)

[sourcecode language="C"]/* Paste your code here (You may delete these lines if not writing code) */[/sourcecode]

Have Your Say

Pingbacks/Trackbacks

1. Count Inversions in an array | JSC

Search

/* Paste your code here (You may delete these lines if not writing code) */

Page 11: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

11/14www.geeksforgeeks.org/archives/3968

Popular Tags

GATEJavaDynamic ProgrammingBacktrackingPattern SearchingDivide & ConquerGraphOperating SystemsRecursion

Popular Posts

All permutations of a given stringMemory Layout of C ProgramsUnderstanding “extern” keyword in CMedian of two sorted arraysTree traversal without recursion and without stack!Structure Member Alignment, Padding and Data PackingIntersection point of two Linked ListsLowest Common Ancestor in a BST.Check if a binary tree is BST or notSorted Linked List to Balanced BST

Page 12: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

12/14www.geeksforgeeks.org/archives/3968

250 Subscribe

Forum Latest Discussion

LIS in nlogn timeLast Post By: kartik

Inside: Interview Questions

tree to fileLast Post By: Dheeraj

Inside: Interview Questions

Page 13: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

13/14www.geeksforgeeks.org/archives/3968

Count internal nodes in a binary treeLast Post By: kartik

Inside: Interview Questions

Ancestor of two given leaf nodesLast Post By: dead

Inside: Trees specific questions

combine elements of an array, so as to minimize weights.Last Post By: rohanag

Inside: Interview Questions

FB interview questionLast Post By: ranganath111

Inside: Interview Questions

Testing of factorial of a numberLast Post By: rukawa

Inside: Interview Questions

numeric puzzleLast Post By: asm

Inside: Algorithms

Forum Categories

Interview QuestionsC/C++ Programming QuestionsAlgorithmsTrees specific questionsLinked List specific questionsMultiple Choice QuestionsObject oriented queriesGPuzzles

Page 14: Count Inversions in an Array _ GeeksforGeeks

5/12/12 Count Inversions in an array | GeeksforGeeks

14/14www.geeksforgeeks.org/archives/3968

Operating SystemsMiscellaneousJava specific QuestionsPerl specific Questions

Recent Comments

Venki on Structure Member Alignment, Padding and Data Packingavi on Structure Member Alignment, Padding and Data Packingatul on A Program to check if strings are rotations of each other or notVenki on Structure Member Alignment, Padding and Data Packingrahul on Dynamic Programming | Set 13 (Cutting a Rod)Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence)Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence)avi on Structure Member Alignment, Padding and Data Packing

@geeksforgeeks, Some rights reservedPowered by WordPress & MooTools, customized by geeksforgeeks team