Vous êtes sur la page 1sur 60

<!DOCTYPE html> <!-- saved from url=(0087)http://stackoverflow.

com/questions/337664/counting-inv ersions-in-an-array/338252#338252 --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>algorithm - Counting inversions in an array - Stack Overflow</title> <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/fav icon.ico"> <link rel="apple-touch-icon image_src" href="http://cdn.sstatic.net/stackove rflow/img/apple-touch-icon.png"> <link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="http://stackoverflow.com/opensearch.xml"> <script type="text/javascript" async="" src="./algorithm - Counting inversio ns in an array - Stack Overflow_files/adzerk1_2_4_43,adzerk2_2_17_45,adzerk3_2_4 _44"></script><script type="text/javascript" async="" src="./algorithm - Countin g inversions in an array - Stack Overflow_files/ga.js"></script><script type="te xt/javascript" async="" src="./algorithm - Counting inversions in an array - Sta ck Overflow_files/quant.js"></script><script type="text/javascript" src="./algor ithm - Counting inversions in an array - Stack Overflow_files/jquery.min.js"></s cript> <script type="text/javascript" src="./algorithm - Counting inversions in an array - Stack Overflow_files/stub.js"></script> <link rel="stylesheet" type="text/css" href="./algorithm - Counting inversio ns in an array - Stack Overflow_files/all.css"> <link rel="canonical" href="http://stackoverflow.com/questions/337664/counti ng-inversions-in-an-array"> <link rel="alternate" type="application/atom+xml" title="Feed for question & #39;Counting inversions in an array&#39;" href="http://stackoverflow.com/feeds/q uestion/337664"> <script type="text/javascript"> StackExchange.ready(function () { StackExchange.using("postValidation", function () { StackExchange.postValidation.initOnBlurAndSubmit($('#post-form') , 2, 'answer'); }); StackExchange.question.init({showAnswerHelp:true,totalCommentCount:2 ,shownCommentCount:2,highlightColor:'#F4A83D',backgroundColor:'#FFF',questionId: 337664}); styleCode(); StackExchange.realtime.subscribeToQuestion('1', '337664'); }); </script> <script type="text/javascript"> StackExchange.init({"stackAuthUrl":"https://stackauth.com","serverTime": 1372754429,"styleCode":true,"enableUserHovercards":true,"site":{"name":"Stack Ov erflow","description":"Q&A for professional and enthusiast programmers","isNotic esTabEnabled":true,"recaptchaPublicKey":"6LdchgIAAAAAAJwGpIzRQSOFaO0pU6s44Xt8aTw c","enableSocialMediaInSharePopup":true},"user":{"fkey":"9336b12e86af343415687d9 e813eec5f","isAnonymous":true}});

StackExchange.using.setCacheBreakers({"js/prettify-full.js":"6c261bebf56 a","js/moderator.js":"68a5f45d34d6","js/full-anon.js":"761e0ff892e6","js/full.js ":"b16edc73d2d1","js/wmd.js":"2f79c03846d5","js/third-party/jquery.autocomplete. min.js":"e5f01e97f7c3","js/mobile.js":"e8e23ad37820","js/help.js":"6e6623243cf6" ,"js/tageditor.js":"450c9e8426fc","js/tageditornew.js":"b6c68ad4c7dd","js/inline -tag-editing.js":"8e84e8a137f7","js/revisions.js":"7273bb714bba","js/review.js": "59e9b73580be","js/tagsuggestions.js":"aa48ef6154df","js/post-validation.js":"bb 996020492a","js/explore-qlist.js":"1c5bbd79b562"}); </script> <script type="text/javascript"> StackExchange.using("gps", function() { StackExchange.gps.init(true); }); </script> <script type="text/javascript"> StackExchange.ready(function () { $('#nav-tour').click(function () { StackExchange.using("gps", function() { StackExchange.gps.track("aboutpage.click", { aboutclick_ location: "headermain" }, true); }); }); }); </script> <script async="" type="text/javascript" src="./algorithm - Counting inversions i n an array - Stack Overflow_files/full-anon.js"></script><script async="" type=" text/javascript" src="./algorithm - Counting inversions in an array - Stack Over flow_files/post-validation.js"></script><script type="text/javascript">//cdn tes t - don't delete! </script><script type="text/javascript" src="./algorithm - Counting inversions i n an array - Stack Overflow_files/adFeedback.js"></script><link rel="stylesheet" href="http://static.adzerk.net/Extensions/adFeedback.css"></head> <body class="question-page"><div style="position: absolute;"><object id="_GPL_sw f" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://downloa d.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="1" height="1"><param name="movie" value="http://contentcache-a.akamaihd.net/items/ it/swf/f.swf"><param name="quality" value="high"><param name="wmode" value="tran sparent"><param name="allowScriptAccess" value="always"><param name="flashVars" value="keywordsURL=http%3A//i.tracksrv.com/kwd%3Fc%3DOjo6c3RhY2tvdmVyZmxvdy5jb20 6ei0xMDIxLTE3MzQ5MQ%253D%253D%26cb%3D_GPL.items.a652c.displayKeywords&amp;keywor ds=stack%20overflow%7Ca%20question%20and%20answer%20site%20for%20professional%20 and%20enthusiast%20programmers%7Cit%27s%7Cfree%7Cno%20registration%20required%7C designing%20an%20algorithm%20to%7Cthe%20following%7Cgiven%20array%7Cfor%20every% 7Cfind%20all%20inversion%20pairs%20such%20that%7Cusing%20merge%20sort%20and%20co pying%20array%20a%20to%20array%7Cand%20then%20comparing%20the%20two%20arrays%7Cb ut%7Chaving%20a%20difficult%20time%20seeing%20how%7Ccan%20use%20this%20to%20find %20the%20number%20of%20inversions%7Cany%20hints%20or%20help%20would%20be%20great ly%20appreciated%7C116k%7Casked%7Cdec%7Cat%7Cthink%20it%27s%20a%20clrs%20exercis e%7Ca%20codility%20question%7Caccepted%7Cthe%20only%20advice%7Ccould%20give%20to %20this%7Cwhich%20looks%20suspiciously%20like%20a%20homework%20question%7Cto%20f irst%7Cmanually%20with%20a%20small%20set%20of%20numbers%7Cand%20then%20write%20d own%20the%20steps%20you%20took%20to%20solve%20the%20problem%7Cthis%20should%20al low%20you%20to%20figure%20out%20a%20generic%20solution%20you%20can%20use%20to%20 write%20the%20code%7Ccommunity%20wiki%7Cfor%20information%7Cthe%20question%7Cact ually%20tagged%20as%7Cthis%20question%7Cbeen%20edited%20yet%20so%7Cmust%20have%2 0tagged%7Cas%20such%20when%7Csubmitted%7Cgood%20point%7Cand%20while%7Capplaud%20 students%20using%20so%20as%20a%20resource%20to%20help%20with%20homework%7Cnot%20 sure%20that%20the%20solution%20should%20be%20spelled%20out%20directly%20for%20th

em%20to%20cut%20and%20paste%7Cseen%20in%20other%20questions%7Cshould%20be%20give n%20enough%20information%20to%20be%20able%20to%20work%20out%20the%20solution%20f or%20himself%7Cin%20other%20words%7Cnot%20answers%7Chopefully%20what%7Cdid%7Cwel l%7Cnot%20a%20bad%20advice%7Cbut%20what%20if%7Ccan%20only%20figure%20out%20a%7Ca lgo%7Cfound%7Clog%7Ctime%20by%20the%20following%20method%7Cmerge%20sort%20array% 20a%20and%20create%20a%20copy%7Ctake%7Cand%20find%20its%20position%20in%20sorted %20array%7Cvia%20a%20binary%20search%7Cthe%20number%20of%20inversions%20for%20th is%20element%20will%20be%20one%20less%20than%20the%20index%20number%20of%20its%2 0position%20in%7Csince%20every%20lower%20number%20that%20appears%20after%20the%2 0first%20element%20of%20a%20will%20be%20an%20inversion%7Caccumulate%20the%20numb er%20of%20inversions%20to%20counter%20variable%7Cremove%7Cfrom%20array%20a%20and %20also%20from%20its%20corresponding%20position%20in%20array%7Crerun%20from%20st ep%7Cuntil%20there%20are%20no%20more%20elements%20in%20a%7Can%20example%20run%20 of%20this%20algorithm%7Coriginal%20array%20a%7Cmerge%20sort%20and%20copy%20to%20 array%7Cand%20binary%20search%20to%20find%7Cin%20the%204th%20position%20of%20arr ay%7Cthus%20there%20are%7Cwe%20know%20this%20because%7Cwas%20in%20the%20first%20 position%20in%20array%20a%7Cthus%20any%20lower%20value%20element%20that%20subseq uently%20appears%20in%20array%20a%20would%20have%20an%20index%20of%7Cin%20this%2 0case%7Cbold%20elements%20are%20removed"><!--[if !IE]> <--> <object id="_GPL_swf " data="http://contentcache-a.akamaihd.net/items/it/swf/f.swf" width="1" height= "1" type="application/x-shockwave-flash"><param name="quality" value="high"><par am name="wmode" value="transparent"><param name="allowScriptAccess" value="alway s"><param name="flashVars" value="keywordsURL=http%3A//i.tracksrv.com/kwd%3Fc%3D Ojo6c3RhY2tvdmVyZmxvdy5jb206ei0xMDIxLTE3MzQ5MQ%253D%253D%26cb%3D_GPL.items.a652c .displayKeywords&amp;keywords=stack%20overflow%7Ca%20question%20and%20answer%20s ite%20for%20professional%20and%20enthusiast%20programmers%7Cit%27s%7Cfree%7Cno%2 0registration%20required%7Cdesigning%20an%20algorithm%20to%7Cthe%20following%7Cg iven%20array%7Cfor%20every%7Cfind%20all%20inversion%20pairs%20such%20that%7Cusin g%20merge%20sort%20and%20copying%20array%20a%20to%20array%7Cand%20then%20compari ng%20the%20two%20arrays%7Cbut%7Chaving%20a%20difficult%20time%20seeing%20how%7Cc an%20use%20this%20to%20find%20the%20number%20of%20inversions%7Cany%20hints%20or% 20help%20would%20be%20greatly%20appreciated%7C116k%7Casked%7Cdec%7Cat%7Cthink%20 it%27s%20a%20clrs%20exercise%7Ca%20codility%20question%7Caccepted%7Cthe%20only%2 0advice%7Ccould%20give%20to%20this%7Cwhich%20looks%20suspiciously%20like%20a%20h omework%20question%7Cto%20first%7Cmanually%20with%20a%20small%20set%20of%20numbe rs%7Cand%20then%20write%20down%20the%20steps%20you%20took%20to%20solve%20the%20p roblem%7Cthis%20should%20allow%20you%20to%20figure%20out%20a%20generic%20solutio n%20you%20can%20use%20to%20write%20the%20code%7Ccommunity%20wiki%7Cfor%20informa tion%7Cthe%20question%7Cactually%20tagged%20as%7Cthis%20question%7Cbeen%20edited %20yet%20so%7Cmust%20have%20tagged%7Cas%20such%20when%7Csubmitted%7Cgood%20point %7Cand%20while%7Capplaud%20students%20using%20so%20as%20a%20resource%20to%20help %20with%20homework%7Cnot%20sure%20that%20the%20solution%20should%20be%20spelled% 20out%20directly%20for%20them%20to%20cut%20and%20paste%7Cseen%20in%20other%20que stions%7Cshould%20be%20given%20enough%20information%20to%20be%20able%20to%20work %20out%20the%20solution%20for%20himself%7Cin%20other%20words%7Cnot%20answers%7Ch opefully%20what%7Cdid%7Cwell%7Cnot%20a%20bad%20advice%7Cbut%20what%20if%7Ccan%20 only%20figure%20out%20a%7Calgo%7Cfound%7Clog%7Ctime%20by%20the%20following%20met hod%7Cmerge%20sort%20array%20a%20and%20create%20a%20copy%7Ctake%7Cand%20find%20i ts%20position%20in%20sorted%20array%7Cvia%20a%20binary%20search%7Cthe%20number%2 0of%20inversions%20for%20this%20element%20will%20be%20one%20less%20than%20the%20 index%20number%20of%20its%20position%20in%7Csince%20every%20lower%20number%20tha t%20appears%20after%20the%20first%20element%20of%20a%20will%20be%20an%20inversio n%7Caccumulate%20the%20number%20of%20inversions%20to%20counter%20variable%7Cremo ve%7Cfrom%20array%20a%20and%20also%20from%20its%20corresponding%20position%20in% 20array%7Crerun%20from%20step%7Cuntil%20there%20are%20no%20more%20elements%20in% 20a%7Can%20example%20run%20of%20this%20algorithm%7Coriginal%20array%20a%7Cmerge% 20sort%20and%20copy%20to%20array%7Cand%20binary%20search%20to%20find%7Cin%20the% 204th%20position%20of%20array%7Cthus%20there%20are%7Cwe%20know%20this%20because% 7Cwas%20in%20the%20first%20position%20in%20array%20a%7Cthus%20any%20lower%20valu e%20element%20that%20subsequently%20appears%20in%20array%20a%20would%20have%20an

%20index%20of%7Cin%20this%20case%7Cbold%20elements%20are%20removed"></object> <! ----> <!--[endif]----> </object></div><div style="position: absolute; top: 0px; left: 0px; width: 1px; height: 1px; z-index: 2147483647;" id="_GPL_e6a00_parent_ div"><object type="application/x-shockwave-flash" id="_GPL_e6a00_swf" data="http ://contentcache-a.akamaihd.net/items/e6a00/storage.swf?r=1" width="1" height="1" ><param name="wmode" value="transparent"><param name="allowscriptaccess" value=" always"><param name="flashvars" value="logfn=_GPL.items.e6a00.log&amp;onload=_GP L.items.e6a00.onload&amp;onerror=_GPL.items.e6a00.onerror&amp;LSOName=gpl"></obj ect></div> <noscript>&lt;div id="noscript-padding"&gt;&lt;/div&gt;</noscript> <div id="notify-container"></div> <div id="overlay-header"></div> <div id="custom-header"></div> <div class="container"> <div id="header" class="headeranon"> <div id="portalLink"> <a class="genu" onclick="StackExchange.ready(function(){genuwine .click();});return false;">Stack Exchange</a> </div> <div id="topbar"> <div id="hlinks"> <span id="hlinks-user"></span> <span id="hlinks-nav"> <a href="http://stackoverflow.com/ users/login?returnurl=%2fquestions%2f337664%2fcounting-inversions-in-an-array%2f 338252">sign up</a> <span class="lsep">|</span> <a href="http://stackoverflow.com/users/login?returnurl=%2fq uestions%2f337664%2fcounting-inversions-in-an-array%2f338252">log in</a> <span class="lsep">|</span> <a href="http://careers.stackoverflow.com/">careers 2.0</a> <span class="lsep">|</span> </span> <span id="hlinks-custom"></span> </div> <div id="hsearch"> <form id="search" action="http://stackoverflow.com/search" m ethod="get" autocomplete="off"> <div> <input autocomplete="off" name="q" class="textbox" p laceholder="search" tabindex="1" type="text" maxlength="240" size="28" value=""> </div> </form> </div> </div> <br class="cbt"> <div id="hlogo"> <a href="http://stackoverflow.com/"> Stack Overflow </a> </div> <div id="hmenus"> <div class="nav mainnavs mainnavsanon"> <ul> <li class="youarehere"><a id="nav-questions" href="h ttp://stackoverflow.com/questions">Questions</a></li>

<li><a id="nav-tags" href="http://stackoverflow.com/ tags">Tags</a></li> <li><a id="nav-tour" href="http://stackoverflow.com/ about">Tour</a></li> <li><a id="nav-users" href="http://stackoverflow.com /users">Users</a></li> </ul> </div> <div class="nav askquestion"> <ul> <li> <a id="nav-askquestion" href="http://stackoverflow.c om/questions/ask">Ask Question</a> </li> </ul> </div> </div> </div>

<div id="content"> <div itemscope="" itemtype="http://schema.org/Article"> <link itemprop="image" href="http://cdn.sstatic.net/stackoverflow/img/apple-touc h-icon.png"> <!--googleoff: snippet--> <div id="herobox-mini"> <div id="hero-content"> <span id="controls"> <a href="http://stackoverflow.com/about" id="tell-me-more" class="bu tton">Tell me more</a> <span id="close"><a title="click to dismiss"></a></span> </span> <div id="blurb"> <span id="site-name">Stack Overflow</span> is a question and answer site for professional and enthusiast programmers. It's 100% free, no registra tion required. </div> </div> <script> $('#tell-me-more').click(function () { var clickSource = $("body").attr("class") + '-mini'; if ($("body").hasClass("questions-page")) { clickSource = 'questionpagemini'; } if ($("body").hasClass("home-page")) { clickSource = 'homepagemini'; } StackExchange.using("gps", function () { StackExchange.gps.track("aboutpage.click", { aboutclick_location : clickSource } , true); }); }); $('#herobox-mini #close').click(function () { StackExchange.using("gps", function () {

StackExchange.gps.track("hero.action", { hero_action_type: "clos e" }, true); }); $.cookie("hero", "none", { path: "/" }); var $hero = $("#herobox-mini"); $hero.slideUp('fast', function () { $hero.remove(); }); return false; }); </script> </div> <!--googleon: snippet--> <div id="question-header"> <h1 itemprop="name"><a href="http://stackoverflow.com/questions/337664/count ing-inversions-in-an-array" class="question-hyperlink">Counting inversions in an array</a></h1> </div> <div id="mainbar">

<div class="question" data-questionid="337664" id="question"> <div class="everyonelovesstackoverflow adzerk-vote" id="adzerk1" ><a href="http://engine.adzerk.net/r?e=eyJhdiI6NDE0LCJhdCI6NCwiY20iOjg0NywiY2giO jExNzgsImNyIjo1OTIwLCJkaSI6ImI2YWFkZTk5NjM4NTQyZjJhNDIxYWY1Mjk1Y2NiYzFkIiwiZG0iO jEsImZjIjo4ODA2LCJmbCI6MjQ0NCwia3ciOiJhbGdvcml0aG0sY29kaWxpdHkiLCJudyI6MjIsInJmI joiaHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3RhZ3MvY29kaWxpdHkvaG90IiwicnYiOjAsInByIjoxN TY4LCJzdCI6ODI3Nywiem4iOjQzLCJ1ciI6Imh0dHA6Ly9jYXJlZXJzLnN0YWNrb3ZlcmZsb3cuY29tL yJ9&s=hja6rjm8ZfNgerXQXUzGFWQhvls" rel="nofollow" target="_blank" title=""><img src="./algorithm - Counting inversions in an array - Stack Overflow_files/60abb4 b317034aa2af0bc697e6f02963.png" title="" alt="" border="0" width="728" height="9 0"></a><div class="adzerk-vote-controls" style="display:none;"><div class="adzer k-vote-option adzerk-vote-up"><div class="adzerk-vote-icon"></div></div><div cla ss="adzerk-vote-option adzerk-vote-down"><div class="adzerk-vote-icon"></div></d iv></div><div class="adzerk-vote-survey" style="display:none;"><form><span>No pr oblem. We won't show you that ad again. Why didn't you like it?</span><ul><li><l abel><input type="radio" value="12" name="downvoteReason">Uninteresting</label>< /li><li><label><input type="radio" value="13" name="downvoteReason">Misleading</ label></li><li><label><input type="radio" value="14" name="downvoteReason">Offen sive</label></li><li><label><input type="radio" value="15" name="downvoteReason" >Repetitive</label></li></ul><a href="http://stackoverflow.com/questions/337664/ counting-inversions-in-an-array/338252#" class="adzerk-vote-cancel">Oops! I didn 't mean to do this.</a></form></div><img height="0px" width="0px" border="0" src ="./algorithm - Counting inversions in an array - Stack Overflow_files/i.gif"></ div> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="337664"> <a class="vote-up-off" title="This question shows research effort; it is use ful and clear">up vote</a> <span class="vote-count-post ">21</span> <a class="vote-down-off" title="This question does not show any research eff ort; it is unclear or not useful">down vote</a>

<a class="star-off" href="http://stackoverflow.com/questions/337664/counting -inversions-in-an-array/338252#" title="This is a favorite question (click again to undo)">favorite</a> <div class="favoritecount"><b>25</b></div> </div> </td> <td class="postcell"> <div> <div class="post-text" itemprop="description"> <p>I'm designing an algorithm to do the following: Given array <code>A[1 ... n]</code>, for every <code>i &lt; j</code>, find all inversion pairs such th at <code>A[i] &gt; A[j]</code>. I'm using merge sort and copying array A to arra y B and then comparing the two arrays, but I'm having a difficult time seeing ho w I can use this to find the number of inversions. Any hints or help would be gr eatly appreciated.</p> </div> <div class="post-taglist"> <a href="http://stackoverflow.com/questions/tagged/algorithm" class="pos t-tag" title="show questions tagged &#39;algorithm&#39;" rel="tag">algorithm</a> <a href="http://stackoverflow.com/questions/tagged/codility" class="post-tag" t itle="show questions tagged &#39;codility&#39;" rel="tag">codility</a> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/q/337664" title="short permalink to this question" class="short-link" id="link-post-337664">share</a><s pan class="lsep">|</span><a href="http://stackoverflow.com/posts/337664/edit" cl ass="suggest-edit-post" title="">improve this question</a></div> </td> <td align="right" class="post-signature"> <div class="user-info user-hover"> <div class="user-action-time"> <a href="http://stackoverflow.com/posts/337664/revis ions" title="show all edits to this post">edited <span title="2012-09-16 15:28:0 4Z" class="relativetime">Sep 16 '12 at 15:28</span></a> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/1288/bill-the-lizard"><div c lass=""><img src="./algorithm - Counting inversions in an array - Stack Overflow _files/fc763c6ff6c160ddad05741e87e517b6" alt="" width="32" height="32"></div></a > </div>

<div class="user-details"> <a href="http://stackoverflow.com/users/1288/bill-the-lizard">Bill t he Lizard</a><span class="mod-flair" title="moderator"> </span><br> <span class="reputation-score" title="reputation score 116342" dir=" ltr">116k</span><span title="85 gold badges"><span class="badge1"></span><span c lass="badgecount">85</span></span><span title="306 silver badges"><span class="b adge2"></span><span class="badgecount">306</span></span><span title="579 bronze badges"><span class="badge3"></span><span class="badgecount">579</span></span> </div> </div> </td> <td class="post-signature owner"> <div class="user-info "> <div class="user-action-time"> asked <span title="2008-12-03 16:07:03Z" cla ss="relativetime">Dec 3 '08 at 16:07</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/27884/el-diablo"><div class= ""><img src="./algorithm - Counting inversions in an array - Stack Overflow_file s/b816036323b4318c5dd371ac96a6e6b1" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/27884/el-diablo">el diablo</ a><br> <span class="reputation-score" title="reputation score" dir="ltr">53 4</span><span title="1 gold badge"><span class="badge1"></span><span class="badg ecount">1</span></span><span title="5 silver badges"><span class="badge2"></span ><span class="badgecount">5</span></span><span title="13 bronze badges"><span cl ass="badge3"></span><span class="badgecount">13</span></span> </div> </div> </td> </tr> </tbody></table> </div> </td> </tr> <tr> <td class="votecell"></td> <td> <div id="comments-337664" class="comments"> <table> <tbody> <tr id="comment-238686" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">4</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td>

<td class="comment-text"><div><span class="comment-copy">I think it's a CLRS exercise...</span> &nbsp;<a href="http://stackoverflow.com/users/33708/mehrd ad-afshari" title="167026 reputation" class="comment-user">Mehrdad Afshari</a> < span class="comment-date" dir="ltr"><a class="comment-link" href="http://stackov erflow.com/questions/337664/counting-inversions-in-an-array/338252#comment238686 _337664"><span title="2009-01-05 18:31:24Z" class="relativetime-clean">Jan 5 '09 at 18:31</span></a></span></div></td> </tr> <tr id="comment-7596910" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">1</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">This is a codil ity question</span> &nbsp;<a href="http://stackoverflow.com/users/62931/roger-nol an" title="9215 reputation" class="comment-user">Roger Nolan</a> <span class="co mment-date" dir="ltr"><a class="comment-link" href="http://stackoverflow.com/que stions/337664/counting-inversions-in-an-array/338252#comment7596910_337664"><spa n title="2011-06-24 10:25:17Z" class="relativetime-clean">Jun 24 '11 at 10:25</s pan></a></span></div></td> </tr> </tbody> </table> </div> </td> </tr> </div> </tbody></table>

<div id="answers"> <a name="tab-top"></a> <div id="answers-header"> <div class="subheader answers-subheader"> <h2> 15 Answers </h2> <div id="tabs"> <a href="http://stackoverflow.com/questions/337664/counting-inve rsions-in-an-array?answertab=active#tab-top" title="Answers with the latest acti vity first">active</a> <a href="http://stackoverflow.com/questions/337664/counting-inversions-in-an-arr ay?answertab=oldest#tab-top" title="Answers in the order they were provided">old est</a> <a class="youarehere" href="http://stackoverflow.com/questions/337664/counting-i nversions-in-an-array?answertab=votes#tab-top" title="Answers with the highest s core first">votes</a> </div> </div> </div>

<a name="337726"></a> <div id="answer-337726" class="answer accepted-answer" data-answerid="337726"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="337726"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">15</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> <span class="vote-accepted-on load-accepted-answer-date" title="load ing when this answer was accepted...">accepted</span> </div> </td>

<td class="answercell"> <div class="post-text"><p>The only advice I could give to this (which looks suspiciously like a homework question ;) ) is to first do it manually with a s mall set of numbers (e.g. 5), and then write down the steps you took to solve th e problem.</p> <p>This should allow you to figure out a generic solution you can use to write t he code.</p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/337726" title="short permalink to this answer" class="short-link" id="link-post-337726">share</a><spa n class="lsep">|</span><a href="http://stackoverflow.com/posts/337726/edit" clas s="suggest-edit-post" title="">improve this answer</a></div> </td> <td align="right" class="post-signature"> <div class="user-info "> <div class="user-action-time"> <a href="http://stackoverflow.com/posts/337726/revis

ions" title="show all edits to this post">edited <span title="2012-10-05 04:19:1 2Z" class="relativetime">Oct 5 '12 at 4:19</span></a> </div> <div class="user-gravatar32"> </div> <div class="user-details"> <br> </div> </div> </td>

<td align="right" class="post-signature">

<div class="user-info"> <div class="user-details"> <span class="community-wiki" title="This post is community owned as of Dec 3 &#39;08 at 16:21. Votes do not generate reputation, and it can be edite d by users with 100 rep"> community wiki </span> </div><br> <div class="user-details"> <a id="history-337726" href="http://stackoverflow.com/posts/337726/r evisions" title="show revision history for this post"> 2 revs, 2 users 91%<br></a><a href="http://stackoverflow.com/users/40410">Andrew Rollings</a> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-337726" class="comments"> <table> <tbody> <tr id="comment-173794" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">1</ span> </td> <td>

&nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">For information ; the question is actually tagged as "homework". This question hasn't been edit ed yet so he must have tagged it as such when he submitted it.</span> &nbsp;<a hr ef="http://stackoverflow.com/users/39277/doctor-jones" title="9445 reputation" c lass="comment-user">Doctor Jones</a> <span class="comment-date" dir="ltr"><a cla ss="comment-link" href="http://stackoverflow.com/questions/337664/counting-inver sions-in-an-array/338252#comment173794_337726"><span title="2008-12-03 16:33:51Z " class="relativetime-clean">Dec 3 '08 at 16:33</span></a></span></div></td> </tr> <tr id="comment-173882" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">3</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Good point... A nd while I applaud students using SO as a resource to help with homework, I'm no t sure that the solution should be spelled out directly for them to cut and past e, as I've seen in other questions. :)</span> &nbsp;<a href="http://stackoverflow .com/users/40410/andrew-rollings" title="7350 reputation" class="comment-user">A ndrew Rollings</a> <span class="comment-date" dir="ltr"><a class="comment-link" href="http://stackoverflow.com/questions/337664/counting-inversions-in-an-array/ 338252#comment173882_337726"><span title="2008-12-03 17:03:47Z" class="relativet ime-clean">Dec 3 '08 at 17:03</span></a></span></div></td> </tr> <tr id="comment-173980" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">4</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">No, it shouldn' t, but he should be given enough information to be able to work out the solution for himself. In other words, hints, not answers.</span> &nbsp;<a href="http://st ackoverflow.com/users/267/lasse-v-karlsen" title="112773 reputation" class="comm ent-user">Lasse V. Karlsen</a> <span class="comment-date" dir="ltr"><a class="co mment-link" href="http://stackoverflow.com/questions/337664/counting-inversionsin-an-array/338252#comment173980_337726"><span title="2008-12-03 17:43:53Z" clas s="relativetime-clean">Dec 3 '08 at 17:43</span></a></span></div></td> </tr> <tr id="comment-173992" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="warm">5</ span> </td>

<td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Which is hopefu lly what I did.</span> &nbsp;<a href="http://stackoverflow.com/users/40410/andrew -rollings" title="7350 reputation" class="comment-user">Andrew Rollings</a> <spa n class="comment-date" dir="ltr"><a class="comment-link" href="http://stackoverf low.com/questions/337664/counting-inversions-in-an-array/338252#comment173992_33 7726"><span title="2008-12-03 17:46:25Z" class="relativetime-clean">Dec 3 '08 at 17:46</span></a></span></div></td> </tr> <tr id="comment-17738631" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">1</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Well, this is n ot a bad advice, but what if I can only figure out a O(n^2) algo?</span> &nbsp;<a href="http://stackoverflow.com/users/888051/alcott" title="2541 reputation" cla ss="comment-user">Alcott</a> <span class="comment-date" dir="ltr"><a class="comm ent-link" href="http://stackoverflow.com/questions/337664/counting-inversions-in -an-array/338252#comment17738631_337726"><span title="2012-10-25 02:20:02Z" clas s="relativetime-clean">Oct 25 '12 at 2:20</span></a></span></div></td> </tr> </tbody> </table> </div> <a id="comments-link-337726" class="comments-link" data-comments-count="1" t itle="expand to show all comments on this post">show <b>1</b> more comment</a> </td> </tr> </tbody></table> </div> <div class="everyonelovesstackoverflow adzerk-vote" id="adzerk3"><a href="http://engine.adzerk.net/r?e=eyJhdiI6NDE0LCJhdCI6NCwiY20iOjI5MTEsImNoIjoxM Tc4LCJjciI6MTA3NjksImRpIjoiNjc1MTIzMGQyZThlNGUwYTlkMGQ4ZDRhOWJhMGU1NDUiLCJkbSI6M SwiZmMiOjE2ODc1LCJmbCI6NzQ3Miwia3ciOiJhbGdvcml0aG0sY29kaWxpdHkiLCJudyI6MjIsInJmI joiaHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3RhZ3MvY29kaWxpdHkvaG90IiwicnYiOjAsInByIjoxN jA0LCJzdCI6ODI3Nywiem4iOjQ0LCJ1ciI6Imh0dHA6Ly9jYXJlZXJzLnN0YWNrb3ZlcmZsb3cuY29tL 2pvYnMvdGVsZWNvbW11dGUifQ&s=5eW8dgWuE6SGbJKZShTKkvRrP20" rel="nofollow" target=" _blank" title=""><img src="./algorithm - Counting inversions in an array - Stack Overflow_files/d893babe671c41118c1fece177e0a21a.jpg" title="" alt="" border="0" width="728" height="90"></a><div class="adzerk-vote-controls" style="display:no ne;"><div class="adzerk-vote-option adzerk-vote-up"><div class="adzerk-vote-icon "></div></div><div class="adzerk-vote-option adzerk-vote-down"><div class="adzer k-vote-icon"></div></div></div><div class="adzerk-vote-survey" style="display:no ne;"><form><span>No problem. We won't show you that ad again. Why didn't you lik e it?</span><ul><li><label><input type="radio" value="12" name="downvoteReason"> Uninteresting</label></li><li><label><input type="radio" value="13" name="downvo teReason">Misleading</label></li><li><label><input type="radio" value="14" name= "downvoteReason">Offensive</label></li><li><label><input type="radio" value="15"

name="downvoteReason">Repetitive</label></li></ul><a href="http://stackoverflow .com/questions/337664/counting-inversions-in-an-array/338252#" class="adzerk-vot e-cancel">Oops! I didn't mean to do this.</a></form></div><img height="0px" widt h="0px" border="0" src="./algorithm - Counting inversions in an array - Stack Ov erflow_files/i(1).gif"></div>

<a name="338252"></a> <div id="answer-338252" class="answer" data-answerid="338252" style=""> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="338252"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">34</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>I've found it in O(n * log n) time by the followin g method.</p> <ol> <li>Merge sort array A and create a copy (array B)</li> <li><p>Take A[1] and find its position in sorted array B via a binary search. Th e number of inversions for this element will be one less than the index number o f its position in B since every lower number that appears after the first elemen t of A will be an inversion. </p> <p>2a. accumulate the number of inversions to counter variable num_inversions.</ p> <p>2b. remove A[1] from array A and also from its corresponding position in arra y B</p></li> <li>rerun from step 2 until there are no more elements in A.</li> </ol> <p>Here's an example run of this algorithm. Original array A = (6, 9, 1, 14, 8, 12 , 3, 2)</p> <p>1: Merge sort and copy to array B</p> <p>B = (1, 2, 3, 6, 8, 9, 12, 14)</p> <p>2: Take A[1] and binary search to find it in array B</p> <p>A[1] = 6</p> <p>B = (1, 2, 3, <strong>6</strong>, 8, 9, 12, 14)</p>

<p>6 is in the 4th position of array B, thus there are 3 inversions. We know thi s because 6 was in the first position in array A, thus any lower value element t hat subsequently appears in array A would have an index of j &gt; i (since i in this case is 1).</p> <p>2.b: Remove A[1] from array A and also from its corresponding position in arr ay B (bold elements are removed).</p> <p>A = (<strong>6,</strong> 9, 1, 14, 8, 12, 3, 2) = (9, 1, 14, 8, 12, 3, 2)</p> <p>B = (1, 2, 3, <strong>6,</strong> 8, 9, 12, 14) = (1, 2, 3, 8, 9, 12, 14)</p> <p>3: Rerun from step 2 on the new A and B arrays.</p> <p>A[1] = 9</p> <p>B = (1, 2, 3, 8, 9, 12, 14)</p> <p>9 is now in the 5th position of array B, thus there are 4 inversions. We know this because 9 was in the first position in array A, thus any lower value eleme nt that subsequently appears would have an index of j &gt; i (since i in this ca se is again 1). Remove A[1] from array A and also from its corresponding position in array B (bo ld elements are removed)</p> <p>A = (<strong>9</strong>, 1, 14, 8, 12, 3, 2) = (1, 14, 8, 12, 3, 2)</p> <p>B = (1, 2, 3, 8, <strong>9</strong>, 12, 14) = (1, 2, 3, 8, 12, 14)</p> <p>Continuing in this vein will give us the total number of inversions for array A once the loop is complete.</p> <p>Step 1 (merge sort) would take O(n * log n) to execute. Step 2 would execute n times and at each execution would perform a binary search that takes O(log n) to run for a total of O(n * log n). Total running time woul d thus be O(n * log n) + O(n * log n) = O(n * log n).</p> <p>Thanks for your help. Writing out the sample arrays on a piece of paper reall y helped to visualize the problem.</p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/338252" title="short permalink to this answer" class="short-link" id="link-post-338252">share</a><spa n class="lsep">|</span><a href="http://stackoverflow.com/posts/338252/edit" clas s="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature owner">

<div class="user-info "> <div class="user-action-time"> answered <span title="2008-12-03 18:36:5 4Z" class="relativetime">Dec 3 '08 at 18:36</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/27884/el-diablo"><div class= ""><img src="./algorithm - Counting inversions in an array - Stack Overflow_file s/b816036323b4318c5dd371ac96a6e6b1" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/27884/el-diablo">el diablo</ a><br> <span class="reputation-score" title="reputation score" dir="ltr">53 4</span><span title="1 gold badge"><span class="badge1"></span><span class="badg ecount">1</span></span><span title="5 silver badges"><span class="badge2"></span ><span class="badgecount">5</span></span><span title="13 bronze badges"><span cl ass="badge3"></span><span class="badgecount">13</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-338252" class="comments"> <table> <tbody> <tr id="comment-9412242" class="comment"> <td></td> <td class="comment-text"><div><span class="comment-copy">why use merge s ort not quick sort?</span> &nbsp;<a href="http://stackoverflow.com/users/888051/a lcott" title="2541 reputation" class="comment-user">Alcott</a> <span class="comm ent-date" dir="ltr"><a class="comment-link" href="http://stackoverflow.com/quest ions/337664/counting-inversions-in-an-array/338252#comment9412242_338252"><span title="2011-10-12 03:21:57Z" class="relativetime-clean">Oct 12 '11 at 3:21</span ></a></span></div></td> </tr> <tr id="comment-11838277" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">4</ span> </td>

<td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">@Alcott Quick s ort has worst running time of O(n^2), when the list is already sorted, and first pivot is chosen every round. Merge sort's worst case is O(n log n)</span> &nbsp; <a href="http://stackoverflow.com/users/482594/user482594" title="2061 reputatio n" class="comment-user">user482594</a> <span class="comment-date" dir="ltr"><a c lass="comment-link" href="http://stackoverflow.com/questions/337664/counting-inv ersions-in-an-array/338252#comment11838277_338252"><span title="2012-02-21 07:09 :29Z" class="relativetime-clean">Feb 21 '12 at 7:09</span></a></span></div></td> </tr> <tr id="comment-17139904" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="warm">5</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">The removal ste p from a standard array makes your algorithm O(n^2), due to shifting the values. (That's why insertion sort is O(n^2))</span> &nbsp;<a href="http://stackoverflow .com/users/257978/kyle-butt" title="2555 reputation" class="comment-user">Kyle B utt</a> <span class="comment-date" dir="ltr"><a class="comment-link" href="http: //stackoverflow.com/questions/337664/counting-inversions-in-an-array/338252#comm ent17139904_338252"><span title="2012-10-02 18:49:41Z" class="relativetime-clean ">Oct 2 '12 at 18:49</span></a></span></div></td> </tr> <tr id="comment-20438411" class="comment"> <td></td> <td class="comment-text"><div><span class="comment-copy">starting with t he first element of array B and counting the elements before it in array A would also give the same result, provided you eliminate them as you described in your answer.</span> &nbsp;<a href="http://stackoverflow.com/users/847917/tutakhail" t itle="110 reputation" class="comment-user">Tutakhail</a> <span class="comment-da te" dir="ltr"><a class="comment-link" href="http://stackoverflow.com/questions/3 37664/counting-inversions-in-an-array/338252#comment20438411_338252"><span title ="2013-01-31 17:51:26Z" class="relativetime-clean">Jan 31 at 17:51</span></a></s pan></div></td> </tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="6424847"></a> <div id="answer-6424847" class="answer" data-answerid="6424847">

<table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="6424847"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">23</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>So here is O(n log n) solution in java. </p> <pre><code>int merge(int[] arr, int[] left, int[] right) { int i = 0, j = 0, count = 0; while (i &lt; left.length || j &lt; right.length) { if (i == left.length) { arr[i+j] = right[j]; j++; } else if (j == right.length) { arr[i+j] = left[i]; i++; } else if (left[i] &lt;= right[j]) { arr[i+j] = left[i]; i++; } else { arr[i+j] = right[j]; count += left.length-i; j++; } } return count; } int invCount(int[] arr) { if (arr.length &lt; 2) return 0; int m = (arr.length + 1) / 2; int left[] = Arrays.copyOfRange(arr, 0, m); int right[] = Arrays.copyOfRange(arr, m, arr.length); return invCount(left) + invCount(right) + merge(arr, left, right); } </code></pre> <p>This is almost normal merge sort, the whole magic is hidden in merge function . Note that while sorting algorithm remove inversions. While merging algorithm counts number of removed inversions (sorted out one migh t say).</p>

<p>The only moment when inversions are removed is when algorithm takes element f rom the right side of an array and merge it to the main array. The number of inversions removed by this operation is the number of elements lef t from the the left array to be merged. :)</p> <p>Hope it's explanatory enough.</p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/6424847" title="short permalink to this answer" class="short-link" id="link-post-6424847">share</a><s pan class="lsep">|</span><a href="http://stackoverflow.com/posts/6424847/edit" c lass="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2011-06-21 11:58:0 8Z" class="relativetime">Jun 21 '11 at 11:58</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/592872/marek-kirejczyk"><div class=""><img src="./algorithm - Counting inversions in an array - Stack Overfl ow_files/26fc0ede527bb4d9f812707dba79416c" alt="" width="32" height="32"></div>< /a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/592872/marek-kirejczyk">Mare k Kirejczyk</a><br> <span class="reputation-score" title="reputation score" dir="ltr">69 3</span><span title="6 silver badges"><span class="badge2"></span><span class="b adgecount">6</span></span><span title="5 bronze badges"><span class="badge3"></s pan><span class="badgecount">5</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-6424847" class="comments"> <table> <tbody> <tr id="comment-8819291" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">3</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">This is such a cleaner method!!!</span> &nbsp;<a href="http://stackoverflow.com/users/611229/red dragonzz" title="508 reputation" class="comment-user">redDragonzz</a> <span clas s="comment-date" dir="ltr"><a class="comment-link" href="http://stackoverflow.co m/questions/337664/counting-inversions-in-an-array/338252#comment8819291_6424847 "><span title="2011-09-06 07:48:38Z" class="relativetime-clean">Sep 6 '11 at 7:4 8</span></a></span></div></td> </tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="543489"></a> <div id="answer-543489" class="answer" data-answerid="543489"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="543489"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">5</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell">

<div class="post-text"><p>I had a question similar to this for homework actu ally. I was restricted that it must have O(nlogn) efficiency.</p> <p>I used the idea you proposed of using Mergesort, since it is already of the c orrect efficiency. I just inserted some code into the merging function that was basically: Whenever a number from the array on the right is being added to the output array , I add to the total number of inversions, the amount of numbers remaining in th e left array.</p> <p>This makes a lot of sense to me now that I've thought about it enough. Your c ounting how many times there is a greater number coming before any numbers.</p> <p>hth.</p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/543489" title="short permalink to this answer" class="short-link" id="link-post-543489">share</a><spa n class="lsep">|</span><a href="http://stackoverflow.com/posts/543489/edit" clas s="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2009-02-12 21:47:4 2Z" class="relativetime">Feb 12 '09 at 21:47</span> </div> <div class="user-gravatar32"> <span class="anonymous-gravatar"></span> </div> <div class="user-details"> statistic<br> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-543489" class="comments"> <table> <tbody> <tr id="comment-15762116" class="comment"> <td></td> <td class="comment-text"><div><span class="comment-copy">i support your answer, essential difference from merge sort is in merge function when element o f 2nd right array gets copied to output array =&gt; increment inversion counter by number of elements remaining in 1st left array</span> &nbsp;<a href="http://st ackoverflow.com/users/647973/alex-salnikov" title="108 reputation" class="commen t-user">Alex.Salnikov</a> <span class="comment-date" dir="ltr"><a class="comment -link" href="http://stackoverflow.com/questions/337664/counting-inversions-in-an -array/338252#comment15762116_543489"><span title="2012-08-07 17:52:02Z" class=" relativetime-clean">Aug 7 '12 at 17:52</span></a></span></div></td> </tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="4821868"></a> <div id="answer-4821868" class="answer" data-answerid="4821868"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="4821868"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">5</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>note that el diablo's solution is O(n^2), since re moving element from an array (and keeping it sorted) is O(n) and you do it O(n) times so it is O(n)*O(n) = O(N^2)</p> </div> <table class="fw">

<tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/4821868" title="short permalink to this answer" class="short-link" id="link-post-4821868">share</a><s pan class="lsep">|</span><a href="http://stackoverflow.com/posts/4821868/edit" c lass="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2011-01-27 21:05:2 7Z" class="relativetime">Jan 27 '11 at 21:05</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/592872/marek-kirejczyk"><div class=""><img src="./algorithm - Counting inversions in an array - Stack Overfl ow_files/26fc0ede527bb4d9f812707dba79416c" alt="" width="32" height="32"></div>< /a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/592872/marek-kirejczyk">Mare k Kirejczyk</a><br> <span class="reputation-score" title="reputation score" dir="ltr">69 3</span><span title="6 silver badges"><span class="badge2"></span><span class="b adgecount">6</span></span><span title="5 bronze badges"><span class="badge3"></s pan><span class="badgecount">5</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-4821868" class="comments"> <table> <tbody>

<tr id="comment-7002284" class="comment"> <td></td> <td class="comment-text"><div><span class="comment-copy">but he's findin g and removing each element with log n binary search</span> &nbsp;<a href="http:/ /stackoverflow.com/users/556617/paul-beusterien" title="5587 reputation" class=" comment-user">Paul Beusterien</a> <span class="comment-date" dir="ltr"><a class= "comment-link" href="http://stackoverflow.com/questions/337664/counting-inversio ns-in-an-array/338252#comment7002284_4821868"><span title="2011-05-18 21:20:02Z" class="relativetime-clean">May 18 '11 at 21:20</span></a></span></div></td> </tr> <tr id="comment-7535058" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">1</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Well almost... as I said removing one element from the array (and keeping it sorted) takes O(n) - you need to move n/2 elements on average one position to the left. One can ea sily solve it by using a binary tree with position statistics (the one that know s how many keys are before any element). This implementation is a bit tricker. T he lead is very good thou.</span> &nbsp;<a href="http://stackoverflow.com/users/5 92872/marek-kirejczyk" title="693 reputation" class="comment-user">Marek Kirejcz yk</a> <span class="comment-date" dir="ltr"><a class="comment-link" href="http:/ /stackoverflow.com/questions/337664/counting-inversions-in-an-array/338252#comme nt7535058_4821868"><span title="2011-06-21 09:07:01Z" class="relativetime-clean" >Jun 21 '11 at 9:07</span></a></span></div></td> </tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="4968085"></a> <div id="answer-4968085" class="answer" data-answerid="4968085"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="4968085"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">3</span> <a class="vote-down-off" title="This answer is not useful">down vote</a>

</div> </td>

<td class="answercell"> <div class="post-text"><p>Check this out: <a href="http://www.cs.jhu.edu/~xf liu/600.363_F03/hw_solution/solution1.pdf" rel="nofollow">http://www.cs.jhu.edu/ ~xfliu/600.363_F03/hw_solution/solution1.pdf</a></p> <p>I hope that it will give you the right answer.</p> <ul> <li>2-3 Inversion part (d)</li> <li>It's running time is O(nlogn)</li> </ul> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/4968085" title="short permalink to this answer" class="short-link" id="link-post-4968085">share</a><s pan class="lsep">|</span><a href="http://stackoverflow.com/posts/4968085/edit" c lass="suggest-edit-post" title="">improve this answer</a></div> </td> <td align="right" class="post-signature"> <div class="user-info user-hover"> <div class="user-action-time"> <a href="http://stackoverflow.com/posts/4968085/revi sions" title="show all edits to this post">edited <span title="2012-01-24 13:30: 30Z" class="relativetime">Jan 24 '12 at 13:30</span></a> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/527987/cosmin-pirvu"><div cl ass=""><img src="./algorithm - Counting inversions in an array - Stack Overflow_ files/a6c0da2f2614e8c66ba52b517076ffaa" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/527987/cosmin-pirvu">Cosmin Pirvu</a><br> <span class="reputation-score" title="reputation score 14787" dir="l tr">14.8k</span><span title="5 gold badges"><span class="badge1"></span><span cl ass="badgecount">5</span></span><span title="17 silver badges"><span class="badg e2"></span><span class="badgecount">17</span></span><span title="32 bronze badge s"><span class="badge3"></span><span class="badgecount">32</span></span> </div>

</div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2011-02-11 10:44:1 7Z" class="relativetime">Feb 11 '11 at 10:44</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/612903/hafsa"><div class=""> <img src="./algorithm - Counting inversions in an array - Stack Overflow_files/1 556c12eb4f68ea8fa6a31724698d909" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/612903/hafsa">Hafsa</a><br> <span class="reputation-score" title="reputation score" dir="ltr">31 </span><span title="1 bronze badge"><span class="badge3"></span><span class="bad gecount">1</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-4968085" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="15151050"></a> <div id="answer-15151050" class="answer" data-answerid="15151050"> <table> <tbody><tr>

<td class="votecell"> <div class="vote"> <input type="hidden" value="15151050"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">3</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>In Python</p> <pre><code># O(n log n) def count_inversion(lst): return merge_count_inversion(lst)[1] def merge_count_inversion(lst): if len(lst) &lt;= 1: return lst, 0 middle = int( len(lst) / 2 ) left, a = merge_count_inversion(lst[:middle]) right, b = merge_count_inversion(lst[middle:]) result, c = merge_count_split_inversion(left, right) return result, (a + b + c) def merge_count_split_inversion(left, right): result = [] count = 0 i, j = 0, 0 left_len = len(left) while i &lt; left_len and j &lt; len(right): if left[i] &lt;= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) count += left_len - i j += 1 result += left[i:] result += right[j:] return result, count #test code input_array_1 input_array_2 input_array_3 input_array_4 input_array_5 input_array_6 input_array_7

= = = = = = =

[] [1] [1, [4, [4, [4, [4,

#0 #0 5] 1] 1, 1, 1,

#0 #1 2, 3, 9] #3 3, 2, 9, 5] #5 3, 2, 9, 1] #8

print count_inversion(input_array_1) print count_inversion(input_array_2) print count_inversion(input_array_3) print count_inversion(input_array_4) print count_inversion(input_array_5) print count_inversion(input_array_6) print count_inversion(input_array_7) </code></pre> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/15151050" title="shor t permalink to this answer" class="short-link" id="link-post-15151050">share</a> <span class="lsep">|</span><a href="http://stackoverflow.com/posts/15151050/edit " class="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info user-hover"> <div class="user-action-time"> answered <span title="2013-03-01 05:20:3 6Z" class="relativetime">Mar 1 at 5:20</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/470682/mkso"><div class="">< img src="./algorithm - Counting inversions in an array - Stack Overflow_files/4c 5d88314e94d0edae14e0adcf0cf135" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/470682/mkso">mkso</a><br> <span class="reputation-score" title="reputation score" dir="ltr">1, 023</span><span title="5 silver badges"><span class="badge2"></span><span class= "badgecount">5</span></span><span title="21 bronze badges"><span class="badge3"> </span><span class="badgecount">21</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-15151050" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="338028"></a> <div id="answer-338028" class="answer" data-answerid="338028"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="338028"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">1</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>The number of inversions in an array is half the t otal distance elements must be moved in order to sort the array. Therefore, it can be computed by sorting the array, maintaining the resulting permutation p[i] , and then computing the sum of abs(p[i]-i)/2. This takes O(n log n) time, whic h is optimal.</p> <p>An alternative method is given at <a href="http://mathworld.wolfram.com/Permu tationInversion.html" rel="nofollow">http://mathworld.wolfram.com/PermutationInv ersion.html</a>. This method is equivalent to the sum of max(0, p[i]-i), which is equal to the sum of abs(p[i]-i])/2 since the total distance elements move lef t is equal to the total distance elements move to the right.</p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/338028" title="short permalink to this answer" class="short-link" id="link-post-338028">share</a><spa n class="lsep">|</span><a href="http://stackoverflow.com/posts/338028/edit" clas s="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2008-12-03 17:36:3 1Z" class="relativetime">Dec 3 '08 at 17:36</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/16480/geoffrey-irving"><div class=""><img src="./algorithm - Counting inversions in an array - Stack Overflo w_files/81b0eda1a755030312d63998980d6b7a" alt="" width="32" height="32"></div></ a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/16480/geoffrey-irving">Geoff rey Irving</a><br> <span class="reputation-score" title="reputation score" dir="ltr">84 1</span><span title="8 silver badges"><span class="badge2"></span><span class="b adgecount">8</span></span><span title="18 bronze badges"><span class="badge3"></ span><span class="badgecount">18</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-338028" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr> </tbody>

</table> </div> </td> </tr> </tbody></table> </div> <a name="11092819"></a> <div id="answer-11092819" class="answer" data-answerid="11092819"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="11092819"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">1</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>Note that the answer by Geoffrey Irving is wrong. </p> <blockquote> <p>The number of inversions in an array is half the total distance elements mu st be moved in order to sort the array. Therefore, it can be computed by sorting the array, maintaining the resulting permutation p[i], and then computing the s um of abs(p[i]-i)/2. This takes O(n log n) time, which is optimal.</p> <p>An alternative method is given at <a href="http://mathworld.wolfram.com/Per mutationInversion.html" rel="nofollow">http://mathworld.wolfram.com/PermutationI nversion.html</a>. This method is equivalent to the sum of max(0, p[i]-i), which is equal to the sum of abs(p[i]-i])/2 since the total distance elements move le ft is equal to the total distance elements move to the right.</p> </blockquote> <p>Take the sequence { 3, 2, 1 } as an example. There are three inversions: (3, 2), (3, 1), (2, 1), so the inversion number is 3. However, according to the quot ed method the answer would have been 2.</p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/11092819" title="shor t permalink to this answer" class="short-link" id="link-post-11092819">share</a> <span class="lsep">|</span><a href="http://stackoverflow.com/posts/11092819/edit " class="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2012-06-19 00:16:4 9Z" class="relativetime">Jun 19 '12 at 0:16</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/1465038/user1465038"><div cl ass=""><img src="./algorithm - Counting inversions in an array - Stack Overflow_ files/032c00e9a19678394b34f4ad6a9a2b53" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/1465038/user1465038">user146 5038</a><br> <span class="reputation-score" title="reputation score" dir="ltr">11 </span><span title="1 bronze badge"><span class="badge3"></span><span class="bad gecount">1</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-11092819" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr> </tbody> </table> </div> </td> </tr>

</tbody></table> </div> <a name="15312592"></a> <div id="answer-15312592" class="answer" data-answerid="15312592"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="15312592"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">1</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>Here is a C code for count inversions</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; 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 &gt; left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left)/2; /* Inversion and number inv_count = inv_count += count will be sum of inversions in left-part, right-part of inversions in merging */ _mergeSort(arr, temp, left, mid); _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 &lt;= mid - 1) &amp;&amp; (j &lt;= right)) { if (arr[i] &lt;= 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 &lt;= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j &lt;= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i=left; i &lt;= 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; } </code></pre> <p>An explanation was given in detail here: <a href="http://www.geeksforgeeks.or g/counting-inversions/" rel="nofollow">http://www.geeksforgeeks.org/counting-inv ersions/</a></p> </div> <table class="fw">

<tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/15312592" title="shor t permalink to this answer" class="short-link" id="link-post-15312592">share</a> <span class="lsep">|</span><a href="http://stackoverflow.com/posts/15312592/edit " class="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2013-03-09 15:46:4 5Z" class="relativetime">Mar 9 at 15:46</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/2020229/banarun"><div class= ""><img src="./algorithm - Counting inversions in an array - Stack Overflow_file s/0b39f658443afa6eaa6b30278dd1cc50" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/2020229/banarun">banarun</a> <br> <span class="reputation-score" title="reputation score" dir="ltr">80 6</span><span title="17 bronze badges"><span class="badge3"></span><span class=" badgecount">17</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-15312592" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr>

</tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="16056139"></a> <div id="answer-16056139" class="answer" data-answerid="16056139"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="16056139"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">1</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>Here is one possible solution with variation of bi nary tree. It adds a field called rightSubTreeSize to each tree node. Keep on in serting number into binary tree in the order they appear in the array. If number goes lhs of node the inversion count for that element would be (1 + rightSubTre eSize). Since all those elements are greater than current element and they would have appeared earlier in the array. If element goes to rhs of a node, just incr ease its rightSubTreeSize. Following is the code. </p> <pre><code>Node { int data; Node* left, *right; int rightSubTreeSize; Node(int data) { rightSubTreeSize = 0; } }; Node* root = null; int totCnt = 0; for(i = 0; i &lt; n; ++i) { Node* p = new Node(a[i]); if(root == null) { root = p; continue; }

Node* q = root; int curCnt = 0; while(q) { if(p-&gt;data &lt;= q-&gt;data) { curCnt += 1 + q-&gt;rightSubTreeSize; if(q-&gt;left) { q = q-&gt;left; } else { q-&gt;left = p; break; } } else { q-&gt;rightSubTreeSize++; if(q-&gt;right) { q = q-&gt;right; } else { q-&gt;right = p; break; } } } totCnt += curCnt; } return totCnt; </code></pre> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/16056139" title="shor t permalink to this answer" class="short-link" id="link-post-16056139">share</a> <span class="lsep">|</span><a href="http://stackoverflow.com/posts/16056139/edit " class="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2013-04-17 09:15:1 8Z" class="relativetime">Apr 17 at 9:15</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/135042/prasadvk"><div class=

""><img src="./algorithm - Counting inversions in an array - Stack Overflow_file s/a464a79778fba707fdaf606f2001394b" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/135042/prasadvk">prasadvk</a ><br> <span class="reputation-score" title="reputation score" dir="ltr">40 2</span><span title="4 silver badges"><span class="badge2"></span><span class="b adgecount">4</span></span><span title="7 bronze badges"><span class="badge3"></s pan><span class="badgecount">7</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-16056139" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="337773"></a> <div id="answer-337773" class="answer" data-answerid="337773"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="337773"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">0</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>The easy O(n^2) answer is to use nested for-loops and increment a counter for every inversion</p> <pre><code>int counter = 0; for(int i = 0; i &lt; n - 1; i++) { for(int j = i+1; j &lt; n; j++) { if( A[i] &gt; A[j] ) { counter++; } } } return counter; </code></pre> <p>Now I suppose you want a more efficient solution, I'll think about it.</p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/337773" title="short permalink to this answer" class="short-link" id="link-post-337773">share</a><spa n class="lsep">|</span><a href="http://stackoverflow.com/posts/337773/edit" clas s="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info user-hover"> <div class="user-action-time"> answered <span title="2008-12-03 16:31:3 8Z" class="relativetime">Dec 3 '08 at 16:31</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/810/mbillard"><div class=""> <img src="./algorithm - Counting inversions in an array - Stack Overflow_files/1 71ef654cf757eac7bcf4668e89bd7c1" alt="" width="32" height="32"></div></a> </div> <div class="user-details">

<a href="http://stackoverflow.com/users/810/mbillard">mbillard</a><b r> <span class="reputation-score" title="reputation score 11880" dir="l tr">11.9k</span><span title="6 gold badges"><span class="badge1"></span><span cl ass="badgecount">6</span></span><span title="37 silver badges"><span class="badg e2"></span><span class="badgecount">37</span></span><span title="63 bronze badge s"><span class="badge3"></span><span class="badgecount">63</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-337773" class="comments"> <table> <tbody> <tr id="comment-173798" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">2</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">For homework qu estions it is best to give helpful suggestions rather than an actual solution. Teach a man to fish.</span> &nbsp;<a href="http://stackoverflow.com/users/39277/d octor-jones" title="9445 reputation" class="comment-user">Doctor Jones</a> <span class="comment-date" dir="ltr"><a class="comment-link" href="http://stackoverfl ow.com/questions/337664/counting-inversions-in-an-array/338252#comment173798_337 773"><span title="2008-12-03 16:35:55Z" class="relativetime-clean">Dec 3 '08 at 16:35</span></a></span></div></td> </tr> <tr id="comment-173804" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">1</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">That's the obvi ous solution every other student will get first, I suppose their teacher wants a better implementation that will get them more points.</span> &nbsp;<a href="http ://stackoverflow.com/users/810/mbillard" title="11880 reputation" class="comment -user">mbillard</a> <span class="comment-date" dir="ltr"><a class="comment-link"

href="http://stackoverflow.com/questions/337664/counting-inversions-in-an-array /338252#comment173804_337773"><span title="2008-12-03 16:37:38Z" class="relative time-clean">Dec 3 '08 at 16:37</span></a></span></div></td> </tr> <tr id="comment-173823" class="comment"> <td></td> <td class="comment-text"><div><span class="comment-copy">Not necessarily , it depends upon the level of the programming course. It's not so straightforw ard for a beginner.</span> &nbsp;<a href="http://stackoverflow.com/users/39277/do ctor-jones" title="9445 reputation" class="comment-user">Doctor Jones</a> <span class="comment-date" dir="ltr"><a class="comment-link" href="http://stackoverflo w.com/questions/337664/counting-inversions-in-an-array/338252#comment173823_3377 73"><span title="2008-12-03 16:44:54Z" class="relativetime-clean">Dec 3 '08 at 1 6:44</span></a></span></div></td> </tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="337828"></a> <div id="answer-337828" class="answer" data-answerid="337828"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="337828"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">0</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>My advice to you would be that copying the array w ould be uneccesary unless you wanted something more than just the number of inve rsions.</p> <p>If you just want to count the number of inversions you should consider that y ou need to loop through the array, and you only care about <strong>pairs</strong > of array elements that are <strong>next</strong> to each other. </p> <p>The first step I would take is to write the problem on paper (actually write an "array" out with some inversions in it). Then solve the problem manually. O nce you've done this you should try to express your solution in pseudo code. As

I said if you consider that you only care about <strong>pairs</strong> of eleme nts that are <strong>next</strong> to each other this will help you simplify you r solution.</p> <p>This is one approach that I used to use when I was a programming student. Wr iting it on paper helps you understand the problem and solution in non programmi ng terms first.</p> <p>Good luck with your assignment. I hope I've been helpful.</p> <p><em>Docta</em></p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/337828" title="short permalink to this answer" class="short-link" id="link-post-337828">share</a><spa n class="lsep">|</span><a href="http://stackoverflow.com/posts/337828/edit" clas s="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info user-hover"> <div class="user-action-time"> answered <span title="2008-12-03 16:44:0 0Z" class="relativetime">Dec 3 '08 at 16:44</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/39277/doctor-jones"><div cla ss=""><img src="./algorithm - Counting inversions in an array - Stack Overflow_f iles/3263eda8fba5d3c9459d9ae572e802d4" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/39277/doctor-jones">Doctor J ones</a><br> <span class="reputation-score" title="reputation score" dir="ltr">9, 445</span><span title="3 gold badges"><span class="badge1"></span><span class="b adgecount">3</span></span><span title="33 silver badges"><span class="badge2"></ span><span class="badgecount">33</span></span><span title="62 bronze badges"><sp an class="badge3"></span><span class="badgecount">62</span></span> </div> </div> </td>

</tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-337828" class="comments"> <table> <tbody> <tr id="comment-175166" class="comment"> <td class="comment-actions"><table><tbody><tr> <td class="comment-score"> <span title="number of &#39;useful comment&#39; votes received" class="cool">1</ span> </td> <td> &nbsp; </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">I think his pro blem is a little bit different than you seem to understand. He's concerned with inversions where two elements are separated as well as adjacent. Otherwise, th is would be a very good answer. :)</span> &nbsp;<a href="http://stackoverflow.co m/users/1288/bill-the-lizard" title="116342 reputation" class="comment-user">Bil l the Lizard<span class="mod-flair" title="moderator"> </span></a> <span class="co mment-date" dir="ltr"><a class="comment-link" href="http://stackoverflow.com/que stions/337664/counting-inversions-in-an-array/338252#comment175166_337828"><span title="2008-12-04 02:58:30Z" class="relativetime-clean">Dec 4 '08 at 2:58</span ></a></span></div></td> </tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="1602514"></a> <div id="answer-1602514" class="answer" data-answerid="1602514"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="1602514"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">0</span> <a class="vote-down-off" title="This answer is not useful">down vote</a>

</div> </td>

<td class="answercell"> <div class="post-text"><p>Use mergesort, in merge step incremeant counter if the number copied to output is from right array. </p> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/1602514" title="short permalink to this answer" class="short-link" id="link-post-1602514">share</a><s pan class="lsep">|</span><a href="http://stackoverflow.com/posts/1602514/edit" c lass="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2009-10-21 18:02:5 7Z" class="relativetime">Oct 21 '09 at 18:02</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/193429/rkatiyar"><div class= ""><img src="./algorithm - Counting inversions in an array - Stack Overflow_file s/ef34918d2d7584f5d6a6c0922697f75a" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/193429/rkatiyar">rkatiyar</a ><br> <span class="reputation-score" title="reputation score" dir="ltr">16 1</span><span title="1 silver badge"><span class="badge2"></span><span class="ba dgecount">1</span></span><span title="9 bronze badges"><span class="badge3"></sp an><span class="badgecount">9</span></span> </div> </div> </td> </tr> </tbody></table>

</td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-1602514" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="13635050"></a> <div id="answer-13635050" class="answer" data-answerid="13635050"> <table> <tbody><tr> <td class="votecell"> <div class="vote"> <input type="hidden" value="13635050"> <a class="vote-up-off" title="This answer is useful">up vote</a> <span class="vote-count-post ">0</span> <a class="vote-down-off" title="This answer is not useful">down vote</a> </div> </td>

<td class="answercell"> <div class="post-text"><p>Since this is an old question, I'll provide my ans wer in C.</p> <pre><code>#include &lt;stdio.h&gt; int count = 0; int inversions(int a[], int len); void mergesort(int a[], int left, int right); void merge(int a[], int left, int mid, int right); int main() { int a[] = { 1, 5, 2, 4, 0 }; printf("%d\n", inversions(a, 5)); }

int inversions(int a[], int len) { mergesort(a, 0, len - 1); return count; } void mergesort(int a[], int left, int right) { if (left &lt; right) { int mid = (left + right) / 2; mergesort(a, left, mid); mergesort(a, mid + 1, right); merge(a, left, mid, right); } } void merge(int a[], int left, int mid, int right) { int i = left; int j = mid + 1; int k = 0; int b[right - left + 1]; while (i &lt;= mid &amp;&amp; j &lt;= right) { if (a[i] &lt;= a[j]) { b[k++] = a[i++]; } else { printf("right element: %d\n", a[j]); count += (mid - i + 1); printf("new count: %d\n", count); b[k++] = a[j++]; } } while (i &lt;= mid) b[k++] = a[i++]; while (j &lt;= right) b[k++] = a[j++]; for (i = left, k = 0; i &lt;= right; i++, k++) { a[i] = b[k]; } } </code></pre> </div> <table class="fw"> <tbody><tr> <td class="vt">

<div class="post-menu"><a href="http://stackoverflow.com/a/13635050" title="shor t permalink to this answer" class="short-link" id="link-post-13635050">share</a> <span class="lsep">|</span><a href="http://stackoverflow.com/posts/13635050/edit " class="suggest-edit-post" title="">improve this answer</a></div> </td>

<td align="right" class="post-signature">

<div class="user-info "> <div class="user-action-time"> answered <span title="2012-11-29 21:27:3 1Z" class="relativetime">Nov 29 '12 at 21:27</span> </div> <div class="user-gravatar32"> <a href="http://stackoverflow.com/users/338982/mbreining"><div class =""><img src="./algorithm - Counting inversions in an array - Stack Overflow_fil es/494d05e14ff76e3a9f0441bdd2de7d5c" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.com/users/338982/mbreining">mbreining< /a><br> <span class="reputation-score" title="reputation score" dir="ltr">3, 178</span><span title="1 gold badge"><span class="badge1"></span><span class="ba dgecount">1</span></span><span title="11 silver badges"><span class="badge2"></s pan><span class="badgecount">11</span></span><span title="21 bronze badges"><spa n class="badge3"></span><span class="badgecount">21</span></span> </div> </div> </td> </tr> </tbody></table> </td> </tr>

<tr> <td class="votecell"></td> <td> <div id="comments-13635050" class="comments dno"> <table> <tbody> <tr><td></td><td></td></tr> </tbody> </table> </div> </td> </tr> </tbody></table> </div> <a name="new-answer"></a> <form id="post-form" action="http://stackoverflow.com/questions/337664/answe r/submit" method="post" class="post-form"> <input type="hidden" id="post-id" value="337664"> <h2 class="space">Your Answer</h2>

<script type="text/javascript"> StackExchange.ready(function() { initTagRenderer("".split(" "), "".split(" ")); prepareEditor({ heartbeatType: 'answer', bindNavPrevention: true, postfix: "", onDemand: true, discardSelector: ".discard-answer" ,immediatelyShowMarkdownHelp:true }); }); </script> <div id="post-editor" class="post-editor"> <div style="position: relative;"> <div class="wmd-container"> <div id="wmd-button-bar" class="wmd-button-bar"><ul id="wmd-button-r ow" class="wmd-button-row"><li id="wmd-bold-button" class="wmd-button" style="le ft: 0px;"><span style="background-position: 0px -20px;"></span></li><li id="wmditalic-button" class="wmd-button" style="left: 25px;"><span style="background-po sition: -20px -20px;"></span></li><li id="wmd-spacer1" class="wmd-spacer" style= "left: 50px;"><span style="background-position: -40px -20px;"></span></li><li id ="wmd-link-button" class="wmd-button" style="left: 75px;"><span style="backgroun d-position: -40px -20px;"></span></li><li id="wmd-quote-button" class="wmd-butto n" style="left: 100px;"><span style="background-position: -60px -20px;"></span>< /li><li id="wmd-code-button" class="wmd-button" style="left: 125px;"><span style ="background-position: -80px -20px;"></span></li><li id="wmd-image-button" class ="wmd-button" style="left: 150px;"><span style="background-position: -100px -20p x;"></span></li><li id="wmd-spacer2" class="wmd-spacer" style="left: 175px;"><sp an style="background-position: -120px -20px;"></span></li><li id="wmd-olist-butt on" class="wmd-button" style="left: 200px;"><span style="background-position: -1 20px -20px;"></span></li><li id="wmd-ulist-button" class="wmd-button" style="lef t: 225px;"><span style="background-position: -140px -20px;"></span></li><li id=" wmd-heading-button" class="wmd-button" style="left: 250px;"><span style="backgro und-position: -160px -20px;"></span></li><li id="wmd-hr-button" class="wmd-butto n" style="left: 275px;"><span style="background-position: -180px -20px;"></span> </li><li id="wmd-spacer3" class="wmd-spacer" style="left: 300px;"><span style="b ackground-position: -200px -20px;"></span></li><li id="wmd-undo-button" class="w md-button" style="left: 325px;"><span style="background-position: -200px -20px;" ></span></li><li id="wmd-redo-button" class="wmd-button" style="left: 350px;"><s pan style="background-position: -220px -20px;"></span></li></ul></div> <textarea id="wmd-input" class="wmd-input" name="post-text" cols="92 " rows="15" tabindex="101" data-min-length=""></textarea> </div> </div> <div class="fl" style="margin-top: 8px; height:24px;">&nbsp;</div> <div id="draft-saved" class="draft-saved community-option fl" style="margintop: 8px; height:24px; display:none;">draft saved</div> <div id="draft-discarded" class="draft-discarded community-option fl" style= "margin-top: 8px; height:24px; display:none;">draft discarded</div>

<div id="wmd-preview" class="wmd-preview"></div> <div></div> <div class="edit-block"> <input id="fkey" name="fkey" type="hidden" value="9336b12e86af343415687d 9e813eec5f"> <input id="author" name="author" type="text"> </div> </div> <div style="position: relative;"> <div class="form-item new-post-login"> <div class="new-login-form"> <div class="new-login-left"> <h3>Sign up or <a id="login-link" href="http://stackover flow.com/users/login?returnurl=%2fquestions%2f337664%2fcounting-inversions-in-an -array%23new-answer">log in</a></h3> <script type="text/javascript"> StackExchange.ready(function () { StackExchange.helpers.onClickDraftSave('#login-l ink'); }); </script> <div class="preferred-login google-login"> <p><span class="icon"></span><span>Sign up using Goo gle</span></p> </div> <div class="preferred-login facebook-login"> <p><span class="icon"></span><span>Sign up using Fac ebook</span></p> </div> <div class="preferred-login stackexchange-login"> <p><span class="icon"></span><span>Sign up using Sta ck Exchange</span></p> </div> </div> <input type="hidden" name="manual-openid" class="manual-open id"> <input type="hidden" name="use-facebook" class="use-facebook " value="false"> <input type="button" class="submit-openid" value="Submit" st yle="display:none"> <div class="new-login-right"> <h3>Post as a guest</h3> <div class="form-item"> <table> <tbody><tr> <script type="text/javascript"> StackExchange.ready(function () { StackExchange.helpers.bindHelpOverlayEvents($('.vm input')); }); </script> <td class="vm"> <div> <label for="display-name">Name</label> <input id="display-name" name="display-name" type="text" siz e="30" maxlength="30" value="" tabindex="105"> </div>

<div> <label for="m-address">Email</label> <input id="m-address" name="m-address" type="text" size="30" maxlength="100" value="" tabindex="106"> <span class="edit-field-overlay">required, but not shown</sp an> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> <script type="text/javascript"> StackExchange.ready( function () { StackExchange.openid.initPostLogin('.new-post-login', '% 2fquestions%2f337664%2fcounting-inversions-in-an-array%23new-answer'); } ); </script> <noscript> &lt;h3&gt;Post as a guest&lt;/h3&gt; &lt;div class="form-item"&gt; &lt;table&gt; &lt;tr&gt; &lt;script type="text/javascript"&gt; StackExchange.ready(function () { StackExchange.helpers.bindHelpOverlayEvents($('.vm input')); }); &lt;/script&gt; &lt;td class="vm"&gt; &lt;div&gt; &lt;label for="display-name"&gt;Name&lt;/label&gt; &lt;input id="display-name" name="display-name" type="text" size="30" maxlength="30" value="" tabindex="105"&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="m-address"&gt;Email&lt;/label&gt; &lt;input id="m-address" name="m-address" type="text" size=" 30" maxlength="100" value="" tabindex="106"&gt; &lt;span class="edit-field-overlay"&gt;required, but not sho wn&lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; </noscript> </div> <div class="form-submit cbt"> <input id="submit-button" type="submit" value="Post Your Answer" tab index="110"> <a href="http://stackoverflow.com/questions/337664/counting-inversio ns-in-an-array/338252#" class="discard-answer dno">discard</a> <p class="privacy-policy-agreement">

By posting your answer, you agree to the <a href="http://stackexchange.com/legal/privacy-policy" target="_blank"> privacy policy</a> and <a href="http://stackexchange.com/legal/terms-of-service" target="_blank ">terms of service</a>. </p> <input type="hidden" name="legalLinksShown" value="1"> </div> </form>

<h2 class="bottom-notice"> Not the answer you're looking for? Browse other questions tagged <a href="http://stackoverflow.com/ques tions/tagged/algorithm" class="post-tag" title="show questions tagged &#39;algor ithm&#39;" rel="tag">algorithm</a> <a href="http://stackoverflow.com/questions/t agged/codility" class="post-tag" title="show questions tagged &#39;codility&#39; " rel="tag">codility</a> or <a href="http://stackoverflow.com/questions/ask">ask your own question</a>. </h2> </div> </div> <div id="sidebar" class="show-votes"> <div class="module question-stats"> <p class="label-key">tagged</p> <div class="tagged"><a href="http://stackoverflow.com/questions/tagged/a lgorithm" class="post-tag" title="show questions tagged &#39;algorithm&#39;" rel ="tag">algorithm</a>&nbsp;<span class="item-multiplier"><span class="item-multip lier-x"></span>&nbsp;<span class="item-multiplier-count">30772</span></span><br> <a href="http://stackoverflow.com/questions/tagged/codility" class="post-tag" ti tle="show questions tagged &#39;codility&#39;" rel="tag">codility</a>&nbsp;<span class="item-multiplier"><span class="item-multiplier-x"></span>&nbsp;<span class ="item-multiplier-count">21</span></span><br> </div> <table id="qinfo"> <tbody><tr> <td><p class="label-key">asked</p></td> <td style="padding-left:10px"><p class="label-key" title="2008-1 2-03 16:07:03Z"><b>4 years ago</b></p></td> </tr> <tr> <td><p class="label-key">viewed</p></td> <td style="padding-left:10px"> <p class="label-key"> <b>30739 times</b> </p> </td> </tr> <tr> <td><p class="label-key">active</p></td> <td style="padding-left:10px"><p class="label-key"><b><a href="h ttp://stackoverflow.com/questions/337664/counting-inversions-in-an-array/338252? lastactivity" class="lastactivity-link" title="2013-04-17 09:15:18Z">2 months ag o</a></b></p></td> </tr> </tbody></table> </div>

<div class="module community-bulletin" data-tracker="cb=1"> <h4>Community Bulletin</h4> <div class="related"> <div class="spacer"> <div class="bulletin-item-type"><a href="http://blog.stackoverflow.c om/?cb=1" class="event-date" target="_blank">blog</a></div> <div class="bulletin-item-content"> <a href="http://blog.stackoverflow.com/2013/07/say-hi-to-nine-of -our-newest-newbies/?cb=1" class="question-hyperlink" target="_blank">Say Hi to Nine of Our Newest Newbies</a> </div> <br class="cbt"> </div> </div> </div> <script type="text/javascript"> var scriptSrc = "http://engine.adzerk.net/z/8277/adzerk1_2_4 _43,adzerk2_2_17_45,adzerk3_2_4_44?keywords=algorithm,codility"; if (document.referrer) { if (/\?/.test(scriptSrc)) scriptSrc += "&"; else scriptSrc += "?"; scriptSrc += "xReferrer=" + document.referrer; } StackExchange.ready(function() { var z = document.createElement("script"); z.type = "text/javascript"; z.async = "true"; z.src = scriptSrc; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s); }); </script> <div class="everyonelovesstackoverflow adzerk-vote" id="adzerk2"><di v id="careersadsdoublehigh" style="display:none;"></div><div class="adzerk-votecontrols" style="display:none;"><div class="adzerk-vote-option adzerk-vote-up">< div class="adzerk-vote-icon"></div></div><div class="adzerk-vote-option adzerk-v ote-down"><div class="adzerk-vote-icon"></div></div></div><div class="adzerk-vot e-survey" style="display:none;"><form><span>No problem. We won't show you that a d again. Why didn't you like it?</span><ul><li><label><input type="radio" value= "12" name="downvoteReason">Uninteresting</label></li><li><label><input type="rad io" value="13" name="downvoteReason">Misleading</label></li><li><label><input ty pe="radio" value="14" name="downvoteReason">Offensive</label></li><li><label><in put type="radio" value="15" name="downvoteReason">Repetitive</label></li></ul><a href="http://stackoverflow.com/questions/337664/counting-inversions-in-an-array /338252#" class="adzerk-vote-cancel">Oops! I didn't mean to do this.</a></form>< /div><img height="0px" width="0px" border="0" src="./algorithm - Counting invers ions in an array - Stack Overflow_files/i(2).gif"></div> <div id="hireme"> <script type="text/javascript"> window.careers_adurl="http://careers.stackoverflow.com/gethired/js",window.caree rs_cssurl="//cdn-careers.sstatic.net/careers/gethired/sidebar.min.css?v=17be6ca0 db4b",window.careers_leaderboardcssurl="//cdn-careers.sstatic.net/careers/gethir ed/ninja.min.css?v=78ccbfa5c59f",window.careers_companycssurl="//cdn-careers.sst atic.net/careers/gethired/company",window.careers_adselector="div.hireme, div#hi reme",StackExchange.ready(function(){$.ajax({url:"//cdn-careers.sstatic.net/care ers/gethired/loader.min.js?v=607ab2dda910",dataType:"script",cache:!0})}) </script>

</div>

<div class="module sidebar-linked"> <h4 id="h-linked">Linked</h4> <div class="linked" data-tracker="lq=1"> <div class="spacer"> <a href="http://stackoverflow.com/q/3836767?lq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">13</div> </a> <a href="http://stackoverflow.com/questions/3836767/interview-question-reverse-p airs?lq=1" class="question-hyperlink">Interview Question: Reverse pairs</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/6523712?lq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">12</div> </a> <a href="http://stackoverflow.com/questions/6523712/calculating-the-number-of-in versions-in-a-permutation?lq=1" class="question-hyperlink">calculating the numbe r of inversions in a permutation</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/4552591?lq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes default">9</div> </a> <a href="http://stackoverflow.com/questions/4552591/how-to-find-the-number-of-in versions-in-an-array?lq=1" class="question-hyperlink">How to find the number of inversions in an array?</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/12658678?lq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">5</div> </a> <a href="http://stackoverflow.com/questions/12658678/swap-the-boxes-in-minimum-m oves?lq=1" class="question-hyperlink">Swap the Boxes in minimum moves</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/9765567?lq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">3</div> </a> <a href="http://stackoverflow.com/questions/9765567/mergesort-implementation-cou nting-number-of-inversions-in-an-array?lq=1" class="question-hyperlink">Mergesor t Implementation.. Counting number of inversions in an array</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/15364607?lq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes default">7</div> </a> <a href="http://stackoverflow.com/questions/15364607/given-an-array-of-integersin-random-order-you-have-to-find-the-minimum-number-o?lq=1" class="question-hype rlink">given an array of integers in random order you have to find the minimum n

umber of swaps to convert it to cyclic sorted array</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/6735102?lq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">3</div> </a> <a href="http://stackoverflow.com/questions/6735102/programming-interview-questi on-array-inversion?lq=1" class="question-hyperlink">Programming interview questi on (array inversion)</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/14720324?lq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">1</div> </a> <a href="http://stackoverflow.com/questions/14720324/compute-the-similarity-betw een-two-lists?lq=1" class="question-hyperlink">Compute the similarity between tw o lists</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/10364630?lq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">1</div> </a> <a href="http://stackoverflow.com/questions/10364630/how-to-find-the-number-of-p air-of-points-that-can-form-a-line-with-positive-slop?lq=1" class="question-hype rlink">How to find the number of pair of points that can form a line with positi ve slope fast?</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/9864206?lq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">0</div> </a> <a href="http://stackoverflow.com/questions/9864206/having-problems-with-inversi on-counting-algorithm?lq=1" class="question-hyperlink">having problems with inve rsion-counting Algorithm</a> </div> <div class="spacer more"> <a href="http://stackoverflow.com/questions/linked/337664?lq=1">see more linked questions</a></div> </div> </div> <div class="module sidebar-related"> <h4 id="h-related">Related</h4> <div class="related" data-tracker="rq=1"> <div class="spacer"> <a href="http://stackoverflow.com/q/4703047?rq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">4</div> </a> <a href="http://stackoverflow.com/questions/4703047/review-of-a-codility-test-pa ir-sum-even-count?rq=1" class="question-hyperlink">review of a codility test - p air_sum_even_count</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/6024614?rq=1" title="Vote score (upvotes - d ownvotes)">

<div class="answer-votes answered-accepted default">8</div> </a> <a href="http://stackoverflow.com/questions/6024614/optimal-inversion-counting-o n-int-arrays?rq=1" class="question-hyperlink">Optimal inversion counting on int arrays</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/6928808?rq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">4</div> </a> <a href="http://stackoverflow.com/questions/6928808/count-inversions-with-mergesort?rq=1" class="question-hyperlink">Count inversions with merge-sort</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/9765567?rq=1" title="Vote score (upvotes - d ownvotes)"> <div class="answer-votes answered-accepted default">3</div> </a> <a href="http://stackoverflow.com/questions/9765567/mergesort-implementation-cou nting-number-of-inversions-in-an-array?rq=1" class="question-hyperlink">Mergesor t Implementation.. Counting number of inversions in an array</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/11497502?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">2</div> </a> <a href="http://stackoverflow.com/questions/11497502/counting-inversions-using-b it?rq=1" class="question-hyperlink">Counting Inversions using BIT</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/12825579?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">0</div> </a> <a href="http://stackoverflow.com/questions/12825579/counting-the-number-of-inve rsions-in-an-array-c?rq=1" class="question-hyperlink">Counting the number of inv ersions in an array, C++</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/14042447?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">3</div> </a> <a href="http://stackoverflow.com/questions/14042447/counting-disk-intersections -using-treeset?rq=1" class="question-hyperlink">Counting Disk Intersections usin g TreeSet</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/14415881?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted extra-large">1162</div> </a> <a href="http://stackoverflow.com/questions/14415881/how-to-pair-socks-from-a-pi le-efficiently?rq=1" class="question-hyperlink">How to pair socks from a pile ef ficiently?</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/14784205?rq=1" title="Vote score (upvotes -

downvotes)"> <div class="answer-votes answered-accepted default">0</div> </a> <a href="http://stackoverflow.com/questions/14784205/count-inversion-in-python-f or-large-integer-array?rq=1" class="question-hyperlink">Count inversion in pytho n (for large integer array)</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/16737810?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">1</div> </a> <a href="http://stackoverflow.com/questions/16737810/is-this-related-to-a-graphcut-edge-bridge-find-the-fast-path-in-time-from-ho?rq=1" class="question-hyperli nk">Is this related to a graph cut-edge (bridge)? Find the fast path in time fro m home to a shop/store</a> </div> </div> </div> </div> <div id="feed-link"> <div id="feed-link-text"><a href="http://stackoverflow.com/feeds/question/33 7664" title="feed of this question and its answers"><span class="feed-icon"></sp an>question feed</a></div> </div> <script type="text/javascript"> StackExchange.ready(function(){$.get('/posts/337664/ivc/7ea7');}); </script> <noscript> &lt;div&gt;&lt;img src="/posts/337664/ivc/7ea7" class="dno" alt="" width="0" height="0"&gt;&lt;/div&gt; </noscript><div style="display:none" id="prettify-lang"></div></div> </div> </div> <div id="footer" class="categories"> <div class="footerwrap"> <div id="footer-menu"> <div class="top-footer-links"> <a href="http://stackoverflow.com/about">about</a> <a href="http://stackoverflow.com/help">help</a> <a href="http://stackoverflow.com/help/badges">badges</a > <a href="http://blog.stackexchange.com/?blb=1">blog</a> <a href="http://chat.stackoverflow.com/">chat</a> <a href="http://data.stackexchange.com/">data</a> <a href="http://stackexchange.com/legal">legal</a> <a href="http://stackexchange.com/legal/privacy-policy">priv acy policy</a> <a href="http://stackexchange.com/about/hiring">jobs</a> <a href="http://engine.adzerk.net/redirect/0/2776/2751/0/4de 3c60f719c4dfcb1a57531c7050090/0">advertising info</a> <a onclick="StackExchange.switchMobile(&quot;on&quot;, &quot ;/questions/337664/counting-inversions-in-an-array/338252&quot;)">mobile</a> <b><a href="http://stackoverflow.com/contact">contact us</a> </b>

<b><a href="http://meta.stackoverflow.com/">feedback</a> </b> </div> <div id="footer-sites"> <table> <tbody><tr> <th colspan="3"> Technology </th> <th> Life / Arts </th> <th> Culture / Recreation </th> <th> Science </th> <th> Other </th> </tr> <tr> <td> <ol> <li><a href="http://stackoverflow.com/" title="professio nal and enthusiast programmers">Stack Overflow</a></li> <li><a href="http://serverfault.com/" title="professiona l system and network administrators">Server Fault</a></li> <li><a href="http://superuser.com/" title="computer enth usiasts and power users">Super User</a></li> <li><a href="http://webapps.stackexchange.com/" title="p ower users of web applications">Web Applications</a></li> <li><a href="http://askubuntu.com/" title="Ubuntu users and developers">Ask Ubuntu</a></li> <li><a href="http://webmasters.stackexchange.com/" title ="pro webmasters">Webmasters</a></li> <li><a href="http://gamedev.stackexchange.com/" title="p rofessional and independent game developers">Game Development</a></li> <li><a href="http://tex.stackexchange.com/" title="users of TeX, LaTeX, ConTeXt, and related typesetting systems">TeX - LaTeX</a></li> </ol></td><td><ol> <li><a href="http://programmers.stackexchange.com/" titl e="professional programmers interested in conceptual questions about software de velopment">Programmers</a></li> <li><a href="http://unix.stackexchange.com/" title="user s of Linux, FreeBSD and other Un*x-like operating systems.">Unix &amp; Linux</a> </li> <li><a href="http://apple.stackexchange.com/" title="pow er users of Apple hardware and software">Ask Different (Apple)</a></li> <li><a href="http://wordpress.stackexchange.com/" title= "WordPress developers and administrators">WordPress Answers</a></li> <li><a href="http://gis.stackexchange.com/" title="carto graphers, geographers and GIS professionals">Geographic Information Systems</a>< /li> <li><a href="http://electronics.stackexchange.com/" titl e="electronics and electrical engineering professionals, students, and enthusias ts">Electrical Engineering</a></li> <li><a href="http://android.stackexchange.com/" title="e nthusiasts and power users of the Android operating system">Android Enthusiasts<

/a></li> <li><a href="http://security.stackexchange.com/" title=" IT security professionals">IT Security</a></li> </ol></td><td><ol> <li><a href="http://dba.stackexchange.com/" title="datab ase professionals who wish to improve their database skills and learn from other s in the community">Database Administrators</a></li> <li><a href="http://drupal.stackexchange.com/" title="Dr upal developers and administrators">Drupal Answers</a></li> <li><a href="http://sharepoint.stackexchange.com/" title ="SharePoint enthusiasts">SharePoint</a></li> <li><a href="http://ux.stackexchange.com/" title="user e xperience researchers and experts">User Experience</a></li> <li><a href="http://mathematica.stackexchange.com/" titl e="users of Mathematica">Mathematica</a></li> <li> <a href="http://stackexchange.com/sites#technology" class="more"> more (13) </a> </li> </ol> </td> <td> <ol> <li><a href="http://photo.stackexchange.com/" title="pro fessional, enthusiast and amateur photographers">Photography</a></li> <li><a href="http://scifi.stackexchange.com/" title="sci ence fiction and fantasy enthusiasts">Science Fiction &amp; Fantasy</a></li> <li><a href="http://cooking.stackexchange.com/" title="p rofessional and amateur chefs">Seasoned Advice (cooking)</a></li> <li><a href="http://diy.stackexchange.com/" title="contr actors and serious DIYers">Home Improvement</a></li> <li> <a href="http://stackexchange.com/sites#lifearts" cl ass="more"> more (13) </a> </li> </ol> </td> <td> <ol> <li><a href="http://english.stackexchange.com/" title="l inguists, etymologists, and serious English language enthusiasts">English Langua ge &amp; Usage</a></li> <li><a href="http://skeptics.stackexchange.com/" title=" scientific skepticism">Skeptics</a></li> <li><a href="http://judaism.stackexchange.com/" title="t hose who base their lives on Jewish law and tradition and anyone interested in l earning more">Mi Yodeya (Judaism)</a></li> <li><a href="http://travel.stackexchange.com/" title="ro ad warriors and seasoned travelers">Travel</a></li> <li><a href="http://christianity.stackexchange.com/" tit le="committed Christians, experts in Christianity and those interested in learni ng more">Christianity</a></li> <li><a href="http://gaming.stackexchange.com/" title="pa ssionate videogamers on all platforms">Arqade (gaming)</a></li>

<li><a href="http://bicycles.stackexchange.com/" title=" people who build and repair bicycles, people who train cycling, or commute on bi cycles">Bicycles</a></li> <li><a href="http://rpg.stackexchange.com/" title="gamem asters and players of tabletop, paper-and-pencil role-playing games">Role-playin g Games</a></li> <li> <a href="http://stackexchange.com/sites#culturerecre ation" class="more"> more (21) </a> </li> </ol> </td> <td> <ol> <li><a href="http://math.stackexchange.com/" title="peop le studying math at any level and professionals in related fields">Mathematics</ a></li> <li><a href="http://stats.stackexchange.com/" title="sta tisticians, data analysts, data miners and data visualization experts">Cross Val idated (stats)</a></li> <li><a href="http://cstheory.stackexchange.com/" title=" theoretical computer scientists and researchers in related fields">Theoretical C omputer Science</a></li> <li><a href="http://physics.stackexchange.com/" title="a ctive researchers, academics and students of physics">Physics</a></li> <li><a href="http://mathoverflow.net/" title="mathematic ians">MathOverflow</a></li> <li> <a href="http://stackexchange.com/sites#science" cla ss="more"> more (7) </a> </li> </ol> </td> <td> <ol> <li><a href="http://stackapps.com/" title="apps, scripts , and development with the Stack Exchange API">Stack Apps</a></li> <li><a href="http://meta.stackoverflow.com/" title="meta -discussion of the Stack Exchange family of Q&amp;A websites">Meta Stack Overflo w</a></li> <li><a href="http://area51.stackexchange.com/" title="pr oposing new sites in the Stack Exchange network">Area 51</a></li> <li><a href="http://careers.stackoverflow.com/">Stack Ov erflow Careers</a></li> </ol> </td> </tr> </tbody></table> </div> </div> <div id="copyright"> site design / logo 2013 stack exchange inc;

user contributions licensed under <a href="http://creativecommon s.org/licenses/by-sa/3.0/" rel="license">cc-wiki</a> with <a href="http://blog.stackoverflow.com/2009/06/attributionrequired/" rel="license">attribution required</a> </div> <div id="footer-flair"> <a href="http://creativecommons.org/licenses/by-sa/3.0/" class=" cc-wiki-link"></a> </div> <div id="svnrev"> rev 2013.7.1.798 </div> </div> </div> <noscript> &lt;div id="noscript-warning"&gt;Stack Overflow works best with JavaScri pt enabled&lt;img src="http://pixel.quantserve.com/pixel/p-c1rF4kxgLUzNc.gif" al t="" class="dno"&gt;&lt;/div&gt; </noscript> <script type="text/javascript">var _gaq=_gaq||[];_gaq.push(['_setAccount','U A-5620270-1']); _gaq.push(['_setCustomVar', 1, 'tags', '|algorithm|codility|']); _gaq.push(['_trackPageview']); var _qevents = _qevents || []; (function(){ var s=document.getElementsByTagName('script')[0]; var ga=document.createElement('script'); ga.type='text/javascript'; ga.async=true; ga.src='http://www.google-analytics.com/ga.js'; s.parentNode.insertBefore(ga,s); var sc=document.createElement('script'); sc.type='text/javascript'; sc.async=true; sc.src='http://edge.quantserve.com/quant.js'; s.parentNode.insertBefore(sc,s); })(); </script> <script type="text/javascript"> _qevents.push({ qacct: "p-c1rF4kxgLUzNc" }); </script> </body></html>