Вы находитесь на странице: 1из 14

5/12/12

Count Inversions in an array | GeeksforGeeks

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.
www.geeksforgeeks.org/archives/3968 1/14

5/12/12

Count Inversions in an array | GeeksforGeeks

itgtnCutitar] itn n eIvon(n r[, n ) { itivcut=0 n n_on ; iti j n , ; fri=0 i<n-1 i+ o( ; ; +) frj=i1 j<n j+ o( +; ; +) i(r[]>arj) fari r[] ivcut+ n_on+; } rtr ivcut eun n_on;

/ Die por t ts aoefntos* * rvr rga o et bv ucin / itmi(n ag,ca* ag) n anit rv hr* rs { itar]={,2,6 4 5; n r[ 1 0 , , } pit( Nme o ivrin ae% \" gtnCutar 5) rnf" ubr f nesos r d n, eIvon(r, ); gthr) eca(; rtr 0 eun ; } 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 be inv1 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 of inversions, we need to add number of inversions in left subarray, right subarray and merge().

How to get number of inversions in merge()?


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

5/12/12

Count Inversions in an array | GeeksforGeeks

In merge process, let i is used for indexing left sub-array and j for right sub-array. At any step in merge(), if a[i] is greater than a[j], then there are (mid i) inversions. because left and right subarrays 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:
www.geeksforgeeks.org/archives/3968 3/14

5/12/12

Count Inversions in an array | GeeksforGeeks

#nld <ti.> icue sdoh #nld <tlbh icue sdi.> it _egSr(n ar] ittm[,itlf,itrgt; n mreotit r[, n ep] n et n ih) itmreitar] ittm[,itlf,itmd itrgt; n eg(n r[, n ep] n et n i, n ih) / Ti fnto srsteiptaryadrtrste * hs ucin ot h nu ra n eun h nme o ivrin i teary* ubr f nesos n h ra / itmreotitar] itarysz) n egSr(n r[, n ra_ie { it*ep=(n *mlo(iefit*ra_ie; n tm it )alcszo(n)arysz) rtr _egSr(r,tm,0 arysz -1; eun mreotar ep , ra_ie ) } / A axlayrcriefnto ta srsteiptaryad * n uiir eusv ucin ht ot h nu ra n rtrstenme o ivrin i teary * eun h ubr f nesos n h ra. / it_egSr(n ar] ittm[,itlf,itrgt n mreotit r[, n ep] n et n ih) { itmd ivcut=0 n i, n_on ; i (ih >lf) f rgt et { / Dvd tearyit toprsadcl _egSrAdonIv) * iie h ra no w at n al mreotnCutn( frec o teprs* o ah f h at / md=(ih +lf)2 i rgt et/;

/ Ivrincutwl b smo ivrin i lf-at rgtpr * neso on il e u f nesos n etpr, ih-a adnme o ivrin i mrig* n ubr f nesos n egn / ivcut =_egSr(r,tm,lf,md; n_on mreotar ep et i) ivcut+ _egSr(r,tm,md1 rgt; n_on = mreotar ep i+, ih) /Mretetoprs/ *eg h w at* ivcut+ mrear tm,lf,md1 rgt; n_on = eg(r, ep et i+, ih)

} rtr ivcut eun n_on;

/ Ti fn mre tosre ary adrtrsivrincuti * hs ut egs w otd ras n eun neso on n teary./ h ras* itmreitar] ittm[,itlf,itmd itrgt n eg(n r[, n ep] n et n i, n ih) { iti j k n , , ; itivcut=0 n n_on ; i=lf;/ ii idxfrlf sbra* et * s ne o et uary/ j=md / ii idxfrrgtsbra* i; * s ne o ih uary/ k=lf;/ ii idxfrrslatmre sbra* et * s ne o eutn egd uary/ wie(i< md-1 & ( < rgt) hl ( = i ) & j = ih) {
www.geeksforgeeks.org/archives/3968 4/14

5/12/12

Count Inversions in an array | GeeksforGeeks

i (r[]< arj) f ari = r[] { tm[+]=ari+; epk+ r[+] } es le { tm[+]=arj+; epk+ r[+] /ti i tik - seaoeepaaindarmfrmre)/ *hs s rcy - e bv xlnto/iga o eg(* ivcut=ivcut+(i -i; n_on n_on md ) }

/ Cp termiigeeet o lf sbra * oy h eann lmns f et uary (fteeaeay t tm* i hr r n) o ep/ wie( < md-1 hl i = i ) tm[+]=ari+; epk+ r[+] / Cp termiigeeet o rgtsbra * oy h eann lmns f ih uary (fteeaeay t tm* i hr r n) o ep/ wie( < rgt hl j = ih) tm[+]=arj+; epk+ r[+] /Cp bc temre eeet t oiia ary/ *oy ak h egd lmns o rgnl ra* fr(=et i< rgt i+ o ilf; = ih; +) ari =tm[] r[] epi; } rtr ivcut eun n_on;

/ Die por t ts aoefntos* * rvr rga o et bv ucin / itmi(n ag,ca* ag) n anit rv hr* rs { itar]={,2,6 4 5; n r[ 1 0 , , } pit( Nme o ivrin ae% \" mreotar 5) rnf" ubr f nesos r d n, egSr(r, ); gthr) eca(; rtr 0 eun ; } Note that above code modifies (or sorts) the input array. If we want to count only inversions then we need to create a copy of original array and call mergeSort() on copy. Time Complexity: O(nlogn) Algorithmic Paradigm: Divide and Conquer

www.geeksforgeeks.org/archives/3968

5/14

5/12/12

Count Inversions in an array | GeeksforGeeks

References: http://www.cs.umd.edu/class/fall2009/cmsc451/lectures/Lec08-inversions.pdf http://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 to solve the same problem.
Send 8 people

You may also like following posts 1. 2. 3. 4. 5. Merge an array of size n into another array of size m+n Given an array A[] and a number x, check for pair in A[] with sum as x Program for array rotation Write a program to reverse an array 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 array insertion 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 ++; else break; Reply 2. jordi says: March 1, 2011 at 1:28 AM theres a linear solution that im looking for.. Reply
www.geeksforgeeks.org/archives/3968 6/14

5/12/12

Count Inversions in an array | GeeksforGeeks

Algoseekar says: April 24, 2011 at 4:59 PM @jordi..i dont think we can do it linearly..?? Reply 3. amit says: November 30, 2010 at 9:32 AM nice question ! Reply 4. Naman Goel says: November 16, 2010 at 11:14 AM We can also use binary search tree method for this here is the code#nld<otem icueisra> uignmsaesd sn aepc t; src nd{ tut oe itdt; n aa nd *et oe lf; nd *ih; oe rgt itr; n c } ; nd *ot=NL; oe ro UL itgtivitvl n e_n(n a) { nd *end =nwnd; oe nwoe e oe nwoe- dt =vl end > aa a; nwoe- lf =NL; end > et UL nwoe- rgt=NL; end > ih UL nwoe- r =0 end > c ; itiv=0 n n ; i(ro) f!ot { ro =nwoe ot end; rtr 0 eun ; } nd *t =ro; oe pr ot
www.geeksforgeeks.org/archives/3968 7/14

5/12/12

Count Inversions in an array | GeeksforGeeks

nd *pr=ro; oe pt ot wiepr hl(t) { pt =pr pr t; i(a <pr>aa fvl t-dt) { iv+ pr>c+; n = t-r 1 pr=pr>et t t-lf; } es le { pr>c+ t-r+; pr=pr>ih; t t-rgt } } i(a <pt-dt) fvl pr>aa { pt-lf =nwoe pr>et end; } es le { pt-rgt=nwoe pr>ih end; } } rtr iv eun n;

itcutivit*ra,n n n on_n(n aryit ) { itiv=0 n n ; friti0ini+ o(n =;<;+) { iv+ gtivaryi) n = e_n(ra[]; } rtr iv eun n; } itmi( n an) { itary]={,,,,,} n ra[ 361245; cu<cutivary6<ed; ot<on_n(ra,)<nl rtr 0 eun ; } Reply J says:
www.geeksforgeeks.org/archives/3968 8/14

5/12/12

Count Inversions in an array | GeeksforGeeks

January 15, 2011 at 9:43 PM Really cool coding. I must learn to code like this. Reply J says: January 15, 2011 at 9:57 PM Memory is leaked in the above program. You cannot just call new and leave it alone. Reply laxman says: March 27, 2011 at 2:45 PM @nama goel ..hi naman can you explain the algorithm..its awesome program. please write the algo. Thanks laxman Reply Venki says: March 30, 2011 at 10:36 AM If I understand the logic correctly, we are constructing BST from the array elements and maintaining a count on each node. The idea here is every parent node must maintain the number of nodes that branched on to it's right side (right count). The above code fails if there are equal element which cause the count to be incremented. Equal nodes won't participate in inversions. The count (rc) will be 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 case complexity is no better than O(n^2). Where as merge sort procedure doesn't depend on data to be sorted. What ever may 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. Reply Decoder says: April 4, 2012 at 3:41 AM
www.geeksforgeeks.org/archives/3968 9/14

5/12/12

Count Inversions in an array | GeeksforGeeks

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

/ Pseyu cd hr (o mydlt teelnsi nt * at or oe ee Yu a eee hs ie f o

Reply Decoder says: April 4, 2012 at 3:44 AM What if we insert equal element to right child of equal element, In this case count won't be incremented. Reply

Comment
Name (Required) Website URI code between sourcecode tags) Email (Required) Your Comment (Writing code? please paste your

[oreoelnug=C] succd agae"" / Pseyu cd hr (o mydlt teelns * at or oe ee Yu a eee hs ie i ntwiigcd)* f o rtn oe / [succd] /oreoe

Have Your Say

Pingbacks/Trackbacks
1. Count Inversions in an array | JSC

Search

www.geeksforgeeks.org/archives/3968

10/14

5/12/12

Count Inversions in an array | GeeksforGeeks

Popular Tags
GATE Java Dynamic Programming Backtracking Pattern Searching Divide & Conquer Graph Operating Systems Recursion

Popular Posts
All permutations of a given string Memory Layout of C Programs Understanding extern keyword in C Median of two sorted arrays Tree traversal without recursion and without stack! Structure Member Alignment, Padding and Data Packing Intersection point of two Linked Lists Lowest Common Ancestor in a BST. Check if a binary tree is BST or not Sorted Linked List to Balanced BST

www.geeksforgeeks.org/archives/3968

11/14

5/12/12

Count Inversions in an array | GeeksforGeeks

250

Subscribe

Forum Latest Discussion


LIS in nlogn time
Last Post By: kartik Inside: Interview Questions

tree to file
Last Post By: Dheeraj Inside: Interview Questions
www.geeksforgeeks.org/archives/3968 12/14

5/12/12

Count Inversions in an array | GeeksforGeeks

Count internal nodes in a binary tree


Last Post By: kartik Inside: Interview Questions

Ancestor of two given leaf nodes


Last 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 question
Last Post By: ranganath111 Inside: Interview Questions

Testing of factorial of a number


Last Post By: rukawa Inside: Interview Questions

numeric puzzle
Last Post By: asm Inside: Algorithms

Forum Categories
Interview Questions C/C++ Programming Questions Algorithms Trees specific questions Linked List specific questions Multiple Choice Questions Object oriented queries GPuzzles
www.geeksforgeeks.org/archives/3968 13/14

5/12/12

Count Inversions in an array | GeeksforGeeks

Operating Systems Miscellaneous Java specific Questions Perl specific Questions

Recent Comments
Venki on Structure Member Alignment, Padding and Data Packing avi on Structure Member Alignment, Padding and Data Packing atul on A Program to check if strings are rotations of each other or not Venki on Structure Member Alignment, Padding and Data Packing rahul 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 reserved Powered by WordPress & MooTools, customized by geeksforgeeks team

www.geeksforgeeks.org/archives/3968

14/14

Вам также может понравиться