<!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

e6a00. top: 0px." id="_GPL_e6a00_parent_ div"><object type="application/x-shockwave-flash" id="_GPL_e6a00_swf" data="http ://contentcache-a.</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.div id="noscript-padding"&gt.%20index%20of%7Cin%20this%20case%7Cbold%20elements%20are%20removed"></object> <! ----> <!--[endif]----> </object></div><div style="position: absolute.e6a00.items.onerror=_GPL. height: 1px.&lt. z-index: 2147483647.">Stack Exchange</a> </div> <div id="topbar"> <div id="hlinks"> <span id="hlinks-user"></span> <span id="hlinks-nav"> <a href="http://stackoverflow.stackoverflow.onerror&amp.items./div&gt.log&amp.}).onload&amp.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.return false.items.click().e6a00.com/questions">Questions</a></li> .net/items/e6a00/storage. left: 0px.akamaihd.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.LSOName=gpl"></obj ect></div> <noscript>&lt.ready(function(){genuwine .com/users/login?returnurl=%2fq uestions%2f337664%2fcounting-inversions-in-an-array%2f338252">log in</a> <span class="lsep">|</span> <a href="http://careers. width: 1px.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/">careers 2.0</a> <span class="lsep">|</span> </span> <span id="hlinks-custom"></span> </div> <div id="hsearch"> <form id="search" action="http://stackoverflow.swf?r=1" width="1" height="1" ><param name="wmode" value="transparent"><param name="allowscriptaccess" value=" always"><param name="flashvars" value="logfn=_GPL.onload=_GP L.

<li><a id="nav-tags" href="http://stackoverflow. true). no registra tion required.sstatic.using("gps".track("aboutpage.attr("class") + '-mini'.com /users">Users</a></li> </ul> </div> <div class="nav askquestion"> <ul> <li> <a id="nav-askquestion" href="http://stackoverflow. }).click(function () { var clickSource = $("body"). </div> </div> <script> $('#tell-me-more').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.click(function () { StackExchange.png"> <!--googleoff: snippet--> <div id="herobox-mini"> <div id="hero-content"> <span id="controls"> <a href="http://stackoverflow. function () { . } if ($("body"). $('#herobox-mini #close'). { aboutclick_location : clickSource } .hasClass("home-page")) { clickSource = 'homepagemini'.com/ tags">Tags</a></li> <li><a id="nav-tour" 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.com/ about">Tour</a></li> <li><a id="nav-users" href="http://stackoverflow.gps.hasClass("questions-page")) { clickSource = 'questionpagemini'. function () { StackExchange.net/stackoverflow/img/apple-touc h-icon. if ($("body"). It's 100% free.using("gps".click". } StackExchange.

slideUp('fast'.com/questions/337664/ counting-inversions-in-an-array/338252#" class="adzerk-vote-cancel">Oops! I didn 't mean to do this. }). function () { $hero. "none". }).remove().Counting inversions in an array .Counting inversions in an array .track("hero.net/r?e=eyJhdiI6NDE0LCJhdCI6NCwiY20iOjg0NywiY2giO jExNzgsImNyIjo1OTIwLCJkaSI6ImI2YWFkZTk5NjM4NTQyZjJhNDIxYWY1Mjk1Y2NiYzFkIiwiZG0iO jEsImZjIjo4ODA2LCJmbCI6MjQ0NCwia3ciOiJhbGdvcml0aG0sY29kaWxpdHkiLCJudyI6MjIsInJmI joiaHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3RhZ3MvY29kaWxpdHkvaG90IiwicnYiOjAsInByIjoxN TY4LCJzdCI6ODI3Nywiem4iOjQzLCJ1ciI6Imh0dHA6Ly9jYXJlZXJzLnN0YWNrb3ZlcmZsb3cuY29tL yJ9&s=hja6rjm8ZfNgerXQXUzGFWQhvls" rel="nofollow" target="_blank" title=""><img src=". { hero_action_type: "clos e" }.Stack Overflow_files/60abb4 b317034aa2af0bc697e6f02963.gps. 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. </script> </div> <!--googleon: snippet--> <div id="question-header"> <h1 itemprop="name"><a href="http://stackoverflow.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.action". { path: "/" })."><form><span>No pr oblem. it is unclear or not useful">down vote</a> . })./algorithm .cookie("hero".</a></form></div><img height="0px" width="0px" border="0" src =". $hero.png" title="" alt="" border="0" width="728" height="9 0"></a><div class="adzerk-vote-controls" style="display:none.adzerk. true).Stack Overflow_files/i.StackExchange."><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. We won't show you that ad again. var $hero = $("#herobox-mini"). return false. 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./algorithm .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. $.

<a class="star-off" href="http://stackoverflow. find all inversion pairs such th at <code>A[i] &gt. I'm using merge sort and copying array A to arra y B and then comparing the two arrays.. for every <code>i &lt.codility&#39.com/questions/tagged/codility" class="post-tag" t itle="show questions tagged &#39.. n]</code>. j</code>.</p> </div> <div class="post-taglist"> <a href="http://stackoverflow.com/questions/tagged/algorithm" class="pos t-tag" title="show questions tagged &#39." rel="tag">algorithm</a> <a href="http://stackoverflow. Any hints or help would be gr eatly appreciated." rel="tag">codility</a> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a 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 .Counting inversions in an array .Stack Overflow _files/fc763c6ff6c160ddad05741e87e517b6" alt="" width="32" height="32"></div></a > </div> ./algorithm . but I'm having a difficult time seeing ho w I can use this to find the number of inversions.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/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/users/1288/bill-the-lizard"><div c lass=""><img src=".algorithm&#39.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. A[j]</code>.

/algorithm .Stack Overflow_file s/b816036323b4318c5dd371ac96a6e6b1" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow. </td></tr> </tbody></table></td> .Counting inversions in an array .com/users/27884/el-diablo"><div class= ""><img src=".useful comment&#39.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.<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. votes received" class="cool">4</ span> </td> <td> &nbsp.

votes received" class="cool">1</ span> </td> <td> &nbsp.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/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-i nversions-in-an-array?answertab=votes#tab-top" title="Answers with the highest s core first">votes</a> </div> </div> </div> .<td class="comment-text"><div><span class="comment-copy">I think it's a CLRS exercise..<a href="http://stackoverflow.useful comment&#39.</span> ±&nbsp.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.<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.. </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">This is a codil ity question</span> ±&nbsp.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.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.

<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.</p> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow. and then write down the steps you took to solve th e problem..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.">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 .com/posts/337726/revis .) ) is to first do it manually with a s mall set of numbers (e.g. 5).</p> <p>This should allow you to figure out a generic solution you can use to write t he code..

2 users 91%<br></a><a href="http://stackoverflow.08 at 16:21.com/posts/337726/r evisions" title="show revision history for this post"> 2 revs. Votes do not generate reputation.useful comment&#39. votes received" class="cool">1</ span> </td> <td> .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. 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/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.

votes received" class="warm">5</ span> </td> .<a href="http://st ackoverflow.useful comment&#39.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/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. hints..<a hr ef="http://stackoverflow.<a href="http://stackoverflow . </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">For information . In other words. :)</span> ±&nbsp.</span> ±&nbsp. This question hasn't been edit ed yet so he must have tagged it as such when he submitted it. but he should be given enough information to be able to work out the solution for himself.. Karlsen</a> <span class="comment-date" dir="ltr"><a class="co mment-link" href="http://stackoverflow.&nbsp.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. votes received" class="cool">4</ span> </td> <td> &nbsp. not answers. the question is actually tagged as "homework".useful comment&#39. A nd while I applaud students using SO as a resource to help with homework. votes received" class="cool">3</ span> </td> <td> &nbsp.</span> ±&nbsp. it shouldn' t. I'm no t sure that the solution should be spelled out directly for them to cut and past e.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. as I've seen in other questions.useful comment&#39.com/users/267/lasse-v-karlsen" title="112773 reputation" class="comm ent-user">Lasse V.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. </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Good point. </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">No.

</span> ±&nbsp./algorithm .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. We won't show you that ad again. </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Which is hopefu lly what I did.<td> &nbsp.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.Stack Overflow_files/d893babe671c41118c1fece177e0a21a.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. this is n ot a bad advice.useful comment&#39. but what if I can only figure out a O(n^2) algo?</span> ±&nbsp.net/r?e=eyJhdiI6NDE0LCJhdCI6NCwiY20iOjI5MTEsImNoIjoxM Tc4LCJjciI6MTA3NjksImRpIjoiNjc1MTIzMGQyZThlNGUwYTlkMGQ4ZDRhOWJhMGU1NDUiLCJkbSI6M SwiZmMiOjE2ODc1LCJmbCI6NzQ3Miwia3ciOiJhbGdvcml0aG0sY29kaWxpdHkiLCJudyI6MjIsInJmI joiaHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3RhZ3MvY29kaWxpdHkvaG90IiwicnYiOjAsInByIjoxN jA0LCJzdCI6ODI3Nywiem4iOjQ0LCJ1ciI6Imh0dHA6Ly9jYXJlZXJzLnN0YWNrb3ZlcmZsb3cuY29tL 2pvYnMvdGVsZWNvbW11dGUifQ&s=5eW8dgWuE6SGbJKZShTKkvRrP20" rel="nofollow" target=" _blank" title=""><img src=".<a 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."><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. votes received" class="cool">1</ span> </td> <td> &nbsp. 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" .Counting inversions in an array .adzerk. </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Well.jpg" title="" alt="" border="0" width="728" height="90"></a><div class="adzerk-vote-controls" style="display:no ne."><form><span>No problem.<a href="http://stackoverflow.

9. 1. accumulate the number of inversions to counter variable num_inversions. 9. 2. 14.</a></form></div><img height="0px" widt h="0px" border="0" src=".</ p> <p>2b. 14)</p> . 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. 12. 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. <strong>6</strong>. 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. 6./algorithm . 8. 8.name="downvoteReason">Repetitive</label></li></ul><a href="http://stackoverflow . 3. 2. 3. 9. 3.</li> </ol> <p>Here's an example run of this algorithm. 2)</p> <p>1: Merge sort and copy to array B</p> <p>B = (1. 12 . Original array A = (6. </p> <p>2a.com/questions/337664/counting-inversions-in-an-array/338252#" class="adzerk-vot e-cancel">Oops! I didn't mean to do this.</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.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.Stack Ov erflow_files/i(1). 8.Counting inversions in an array . 12.

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

com/users/27884/el-diablo"><div class= ""><img src=".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/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.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.Counting inversions in an array .<a href="http://stackoverflow.<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. votes received" class="cool">4</ span> </td> .useful comment&#39.Stack Overflow_file s/b816036323b4318c5dd371ac96a6e6b1" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow./algorithm .

<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>

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"> .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.<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.<a href="http://stackoverflow. votes received" class="cool">3</ span> </td> <td> &nbsp.useful comment&#39. </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">This is such a cleaner method!!!</span> ±&nbsp.

the amount of numbers remaining in th e left array.</p> <p>I used the idea you proposed of using Mergesort.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> .</p> <p>hth. I add to the total number of inversions. Your c ounting how many times there is a greater number coming before any numbers. 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 .<div class="post-text"><p>I had a question similar to this for homework actu ally.</p> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow.</p> <p>This makes a lot of sense to me now that I've thought about it enough.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. I was restricted that it must have O(nlogn) efficiency. since it is already of the c orrect efficiency.

essential difference from merge sort is in merge function when element o f 2nd right array gets copied to output array =&gt. 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"> .<a href="http://st ackoverflow.<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.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). increment inversion counter by number of elements remaining in 1st left array</span> ±&nbsp.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.

/algorithm .com/users/592872/marek-kirejczyk"><div class=""><img src=".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.Stack Overfl ow_files/26fc0ede527bb4d9f812707dba79416c" alt="" width="32" height="32"></div>< /a> </div> <div class="user-details"> <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.Counting inversions in an array .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> .<tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow.

you need to move n/2 elements on average one position to the left.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> .</span> ±&nbsp.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/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. as I said removing one element from the array (and keeping it sorted) takes O(n) .<a href="http://stackoverflow.<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.. </td></tr> </tbody></table></td> <td class="comment-text"><div><span class="comment-copy">Well almost. votes received" class="cool">1</ span> </td> <td> &nbsp.<a href="http:/ /stackoverflow.useful comment&#39. 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)..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. This implementation is a bit tricker. T he lead is very good thou.

cs.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.363_F03/hw_solution/solution1.cs.pdf" rel="nofollow">http://www.jhu.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> .Counting inversions in an array .363_F03/hw_solution/solution1.</div> </td> <td class="answercell"> <div class="post-text"><p>Check this out: <a href="http://www.</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.edu/ ~xfliu/600.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/users/527987/cosmin-pirvu"><div cl ass=""><img src=".pdf</a></p> <p>I hope that it will give you the right answer.com/users/527987/cosmin-pirvu">Cosmin Pirvu</a><br> <span class="reputation-score" title="reputation score 14787" dir="l tr">14.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.edu/~xf liu/600.Stack Overflow_ files/a6c0da2f2614e8c66ba52b517076ffaa" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.jhu./algorithm .

com/users/612903/hafsa"><div class=""> <img src="./algorithm .</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">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> .Stack Overflow_files/1 556c12eb4f68ea8fa6a31724698d909" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.Counting inversions in an array .

c = merge_count_split_inversion(left.append(right[j]) count += left_len . right) return result. 0 middle = int( len(lst) / 2 ) left.<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. [4. right): result = [] count = 0 i. 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. 1. 9.= right[j]: result. j = 0. [4. a = merge_count_inversion(lst[:middle]) right. 9. 3. 9] #3 3. 1] #8 . 2. (a + b + c) def merge_count_split_inversion(left. 0 left_len = len(left) while i &lt. 1. #0 #0 5] 1] 1. b = merge_count_inversion(lst[middle:]) result.i j += 1 result += left[i:] result += right[j:] return result.append(left[i]) i += 1 else: result.= 1: return lst. left_len and j &lt. len(right): if left[i] &lt. [4. 5] #5 3. #0 #1 2. 2. [4.

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/users/470682/mkso"><div class="">< img src="./algorithm .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. 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> .Stack Overflow_files/4c 5d88314e94d0edae14e0adcf0cf135" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <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.Counting inversions in an array .com/users/470682/mkso">mkso</a><br> <span class="reputation-score" title="reputation score" dir="ltr">1.

This takes O(n log n) time.wolfram. Therefore.html</a>. whic h is optimal.com/Permu tationInversion.</p> </div> <table class="fw"> <tbody><tr> <td class="vt"> .</p> <p>An alternative method is given at <a href="http://mathworld. This method is equivalent to the sum of max(0. it can be computed by sorting the array.html" rel="nofollow">http://mathworld.com/PermutationInv ersion. 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[i]-i). maintaining the resulting permutation p[i] .wolfram.<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. and then computing the sum of abs(p[i]-i)/2.

com/users/16480/geoffrey-irving"><div class=""><img src=".Stack Overflo w_files/81b0eda1a755030312d63998980d6b7a" alt="" width="32" height="32"></div></ a> </div> <div class="user-details"> <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./algorithm .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> .<div class="post-menu"><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.Counting inversions in an array .

1 } as an example. 2). (3.</p> </blockquote> <p>Take the sequence { 3. p[i]-i).</p> <p>An alternative method is given at <a href="http://mathworld. which is optimal. Therefore.html" rel="nofollow">http://mathworld. This takes O(n log n) time. However.com/PermutationI nversion. 2.</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. 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. maintaining the resulting permutation p[i]. it can be computed by sorting the array.html</a>. according to the quot ed method the answer would have been 2.</p> </div> <table class="fw"> <tbody><tr> <td class="vt"> . </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. This method is equivalent to the sum of max(0.com/Per mutationInversion.wolfram. 1). 1). and then computing the s um of abs(p[i]-i)/2. so the inversion number is 3.wolfram. There are three inversions: (3. (2.

com/users/1465038/user1465038"><div cl ass=""><img src=".<div class="post-menu"><a href="http://stackoverflow.Counting inversions in an array .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.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> ./algorithm .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.

mid). right). /* This function sorts the input array and returns the number of inversions in the array */ int mergeSort(int arr[].</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. right). #include &lt. left. right-part of inversions in merging */ _mergeSort(arr. int _mergeSort(int arr[]. left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left)/2. temp. temp. mid+1. */ int _mergeSort(int arr[]. int mid.stdio. inv_count = 0. int left. } /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. temp. int right).h&gt. return _mergeSort(arr. int temp[]. /* Inversion and number inv_count = inv_count += count will be sum of inversions in left-part. int array_size) { int *temp = (int *)malloc(sizeof(int)*array_size).h&gt. left. int temp[]. temp. int right). } . array_size . _mergeSort(arr. int merge(int arr[]. if (right &gt. 0. int right) { int mid. int left. mid+1. int left.1). int temp[]. /*Merge the two parts*/ inv_count += merge(arr.stdlib.

int left. /* i is index for left subarray*/ j = mid. 6. /* i is index for resultant merged subarray*/ while ((i &lt. /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j &lt. (j &lt. } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i &lt.i).= right)) { if (arr[i] &lt. mergeSort(arr. 4.= arr[j]) { temp[k++] = arr[i++].or g/counting-inversions/" rel="nofollow">http://www. 5)).*/ int merge(int arr[].geeksforgeeks. return inv_count. } else { temp[k++] = arr[j++]. int mid. } </code></pre> <p>An explanation was given in detail here: <a href="http://www.&amp. i++) arr[i] = temp[i].= right. printf(" Number of inversions are %d \n".1) &amp. 20.1) temp[k++] = arr[i++]. j. /*this is tricky -.geeksforgeeks. 5}. /*Copy back the merged elements to original array*/ for (i=left. getchar().= right) temp[k++] = arr[j++]. return 0.= mid .= mid . k. char** args) { int arr[] = {1. int temp[]. } /* Driver progra to test above functions */ int main(int argv.return inv_count. i &lt. } /* This funt merges two sorted arrays and returns inversion count in the arrays. int right) { int i.see above explanation/diagram for merge()*/ inv_count = inv_count + (mid . i = left. int inv_count = 0.org/counting-inv ersions/</a></p> </div> <table class="fw"> . /* i is index for right subarray*/ k = left.

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">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> .Counting inversions in an array ./algorithm .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"><div class= ""><img src=".<tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow.

i &lt. ++i) { Node* p = new Node(a[i]). int totCnt = 0. if(root == null) { root = p. continue. It adds a field called rightSubTreeSize to each tree node. for(i = 0. Keep on in serting number into binary tree in the order they appear in the array. just incr ease its rightSubTreeSize. Node* left. If element goes to rhs of a node. n. 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. </p> <pre><code>Node { int data. Node* root = null. int rightSubTreeSize. } . *right. } }. Following is the code.</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. Node(int data) { rightSubTreeSize = 0.

} return totCnt.right) { q = q-&gt. break. } else { q-&gt. } } } totCnt += curCnt.rightSubTreeSize.Node* q = root. if(q-&gt.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. } else { q-&gt.data) { curCnt += 1 + q-&gt.= q-&gt.right.right = p.rightSubTreeSize++.data &lt.left) { q = q-&gt.left = p.com/users/135042/prasadvk"><div class= .left.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. if(q-&gt. </code></pre> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow. } } else { q-&gt. while(q) { if(p-&gt. int curCnt = 0. break.

Stack Overflow_file s/a464a79778fba707fdaf606f2001394b" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.""><img src=".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> ./algorithm .Counting inversions in an array .

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. i++) { for(int j = i+1. </code></pre> <p>Now I suppose you want a more efficient solution. for(int i = 0. i &lt.Stack Overflow_files/1 71ef654cf757eac7bcf4668e89bd7c1" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> . A[j] ) { counter++.</p> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow.<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.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. } } } return counter. n./algorithm . I'll think about it. n .com/users/810/mbillard"><div class=""> <img src=". j++) { if( A[i] &gt.1. j &lt.Counting inversions in an array .

useful comment&#39. </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.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.<a href="http://stackoverflow.com/users/810/mbillard">mbillard</a><b r> <span class="reputation-score" title="reputation score 11880" dir="l tr">11.<a href="http://stackoverflow. votes received" class="cool">1</ span> </td> <td> &nbsp.useful comment&#39.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.com/users/810/mbillard" title="11880 reputation" class="comment -user">mbillard</a> <span class="comment-date" dir="ltr"><a class="comment-link" .</span> ±&nbsp. I suppose their teacher wants a better implementation that will get them more points.<a href="http ://stackoverflow.</span> ±&nbsp. votes received" class="cool">2</ 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.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.

<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#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. As . Then solve the problem manually.</p> <p>If you just want to count the number of inversions you should consider that y ou need to loop through the array.href="http://stackoverflow. 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). O nce you've done this you should try to express your solution in pseudo code. It's not so straightforw ard for a beginner.</span> ±&nbsp.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>This is one approach that I used to use when I was a programming student.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.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.Stack Overflow_f iles/3263eda8fba5d3c9459d9ae572e802d4" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.Counting inversions in an array .com/users/39277/doctor-jones">Doctor J ones</a><br> <span class="reputation-score" title="reputation score" dir="ltr">9.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.</p> <p><em>Docta</em></p> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow.</p> <p>Good luck with your assignment./algorithm . I hope I've been helpful.com/users/39277/doctor-jones"><div cla ss=""><img src=". 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> . Wr iting it on paper helps you understand the problem and solution in non programmi ng terms first.

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> . </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.</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. votes received" class="cool">1</ span> </td> <td> &nbsp. :)</span> ±&nbsp. Otherwise. th is would be a very good answer.useful comment&#39. He's concerned with inversions where two elements are separated as well as adjacent.<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.

Stack Overflow_file s/ef34918d2d7584f5d6a6c0922697f75a" alt="" width="32" height="32"></div></a> </div> <div class="user-details"> <a href="http://stackoverflow.</div> </td> <td class="answercell"> <div class="post-text"><p>Use mergesort.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> .com/users/193429/rkatiyar"><div class= ""><img src=".Counting inversions in an array . </p> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow. in merge step incremeant counter if the number copied to output is from right array.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./algorithm .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.

int inversions(int a[]. 2. } . inversions(a. printf("%d\n".</p> <pre><code>#include &lt. void mergesort(int a[]. int main() { int a[] = { 1. 0 }.stdio. I'll provide my ans wer in C. void merge(int a[]. 5. int right).h&gt. int mid. 5)). int len). int count = 0. int left. int left.</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. int right). 4.

mergesort(a.left + 1]. while (i &lt. merge(a.= right) { if (a[i] &lt. int left. 0. int len) { mergesort(a. mid + 1. mid.= right.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. j &lt. mid).int inversions(int a[]. i++.&amp. int right) { if (left &lt. } } </code></pre> </div> <table class="fw"> <tbody><tr> <td class="vt"> <div class="post-menu"><a href="http://stackoverflow. int left. } void mergesort(int a[]. left.= mid) b[k++] = a[i++]. int k = 0. left. b[k++] = a[j++]. for (i = left. } } void merge(int a[].i + 1). count += (mid . right). return count. } else { printf("right element: %d\n". count). printf("new count: %d\n".com/posts/13635050/edit " class="suggest-edit-post" title="">improve this answer</a></div> </td> . } } while (i &lt.= mid &amp. int mid. a[j]). k = 0. right) { int mid = (left + right) / 2.= a[j]) { b[k++] = a[i++]. while (j &lt. mergesort(a. int right) { int i = left. k++) { a[i] = b[k]. i &lt. right). len .1). int j = mid + 1. int b[right .= right) b[k++] = a[j++].

com/users/338982/mbreining">mbreining< /a><br> <span class="reputation-score" title="reputation score" dir="ltr">3./algorithm .Counting inversions in an array . 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> .<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.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"><div class =""><img src=".

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

</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> .ready(function () { StackExchange.com/users/login?returnurl=%2fquestions%2f337664%2fcounting-inversions-in-an -array%23new-answer">log in</a></h3> <script type="text/javascript"> StackExchange."> <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.ready(function () { StackExchange. }).helpers.<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.helpers.onClickDraftSave('#login-l ink').bindHelpOverlayEvents($('. }). </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.vm input')).

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

<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. " rel="tag">codility</a> or <a href="http://stackoverflow. </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/legal/terms-of-service" target="_blank ">terms of service</a>.algorithm&#39.com/legal/privacy-policy" target="_blank"> privacy policy</a> and <a href="http://stackexchange.By posting your answer.codility&#39.algor ithm&#39. </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." rel="tag">algorithm</a> <a href="http://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> .<span class="item-multiplier"><span class="item-multiplier-x">×</span>&nbsp.com/questions/tagged/a lgorithm" class="post-tag" title="show questions tagged &#39. you agree to the <a href="http://stackexchange.<span class="item-multiplier"><span class="item-multip lier-x">×</span>&nbsp.codility&#39.com/questions/ask">ask your own question</a>.com/ques tions/tagged/algorithm" class="post-tag" title="show questions tagged &#39.com/questions/tagged/codility" class="post-tag" ti tle="show questions tagged &#39." rel="tag">codility</a>&nbsp.<span class="item-multiplier-count">30772</span></span><br> <a href="http://stackoverflow." rel ="tag">algorithm</a>&nbsp.com/questions/t agged/codility" class="post-tag" title="show questions tagged &#39.

createElement("script").insertBefore(z.window. else scriptSrc += "?".dataType:"script".cache:!0})}) </script> . if (document./algorithm .ready(function() { var z = document.sstatic. We won't show you that a d again. div#hi reme".sst atic. s).hireme.min. </script> <div class="everyonelovesstackoverflow adzerk-vote" id="adzerk2"><di v id="careersadsdoublehigh" style="display:none.src = scriptSrc.gif"></div> <div id="hireme"> <script type="text/javascript"> window.net/care ers/gethired/loader.adzerk3_2_4_44?keywords=algorithm.min.getElementsByTagName("script")[0].css?v=17be6ca0 db4b". 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."></div><div class="adzerk-votecontrols" style="display:none.c om/?cb=1" class="event-date" target="_blank">blog</a></div> <div class="bulletin-item-content"> <a href="http://blog.parentNode.net/careers/gethired/sidebar.net/z/8277/adzerk1_2_4 _43.min.referrer) { if (/\?/.net/careers/gethir ed/ninja.stackoverflow.<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.test(scriptSrc)) scriptSrc += "&". z.Counting invers ions in an array .type = "text/javascript".ready(function(){$. z.careers_adurl="http://careers.net/careers/gethired/company".window.css?v=78ccbfa5c59f".adzerk2_2_17_45.Stack Overflow_files/i(2).codility".</a></form>< /div><img height="0px" width="0px" border="0" src=".js?v=607ab2dda910".caree rs_cssurl="//cdn-careers. z.sstatic. scriptSrc += "xReferrer=" + document.StackExchange.careers_adselector="div. })."><form><span>No problem. var s = document.referrer.adzerk.window.stackoverflow.sstatic.stackoverflow. s.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. } StackExchange.careers_companycssurl="//cdn-careers."><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.careers_leaderboardcssurl="//cdn-careers.window.ajax({url:"//cdn-careers.async = "true".com/gethired/js".com/questions/337664/counting-inversions-in-an-array /338252#" class="adzerk-vote-cancel">Oops! I didn't mean to do this.

.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/q/9765567?lq=1" title="Vote score (upvotes .com/q/3836767?lq=1" title="Vote score (upvotes . Counting number of inversions in an array</a> </div> <div class="spacer"> <a href="http://stackoverflow.d ownvotes)"> <div class="answer-votes default">9</div> </a> <a href="http://stackoverflow.d ownvotes)"> <div class="answer-votes answered-accepted default">12</div> </a> <a href="http://stackoverflow.com/q/4552591?lq=1" title="Vote score (upvotes .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 .d ownvotes)"> <div class="answer-votes answered-accepted default">13</div> </a> <a href="http://stackoverflow.d ownvotes)"> <div class="answer-votes answered-accepted default">3</div> </a> <a href="http://stackoverflow.</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/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/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/6523712?lq=1" title="Vote score (upvotes .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/questions/9765567/mergesort-implementation-cou nting-number-of-inversions-in-an-array?lq=1" class="question-hyperlink">Mergesor t Implementation.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/4703047?rq=1" title="Vote score (upvotes .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/6024614?rq=1" title="Vote score (upvotes .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.d ownvotes)"> <div class="answer-votes answered-accepted default">0</div> </a> <a href="http://stackoverflow.d ownvotes)"> .d ownvotes)"> <div class="answer-votes answered-accepted default">4</div> </a> <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/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.d ownvotes)"> <div class="answer-votes answered-accepted default">3</div> </a> <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/6735102?lq=1" title="Vote score (upvotes .com/q/14720324?lq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">1</div> </a> <a href="http://stackoverflow.p air_sum_even_count</a> </div> <div class="spacer"> <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 .umber of swaps to convert it to cyclic sorted array</a> </div> <div class="spacer"> <a href="http://stackoverflow.com/q/9864206?lq=1" title="Vote score (upvotes .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/6928808?rq=1" title="Vote score (upvotes .com/q/14784205?rq=1" title="Vote score (upvotes - .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/14042447?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">3</div> </a> <a href="http://stackoverflow..<div class="answer-votes answered-accepted default">8</div> </a> <a href="http://stackoverflow. Counting number of inversions in an array</a> </div> <div class="spacer"> <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.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.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/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/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/11497502/counting-inversions-using-b it?rq=1" class="question-hyperlink">Counting Inversions using BIT</a> </div> <div class="spacer"> <a href="http://stackoverflow. C++</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/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/11497502?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">2</div> </a> <a href="http://stackoverflow.d ownvotes)"> <div class="answer-votes answered-accepted default">4</div> </a> <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.}).com/about">about</a> <a href="http://stackoverflow.com/help/badges">badges</a > <a href="http://blog.com/?blb=1">blog</a> <a href="http://chat.com/legal/privacy-policy">priv acy policy</a> <a href="http://stackexchange.on&quot.com/help">help</a> <a href="http://stackoverflow.net/redirect/0/2776/2751/0/4de 3c60f719c4dfcb1a57531c7050090/0">advertising info</a> <a onclick="StackExchange.stackexchange.stackexchange.com/">data</a> <a href="http://stackexchange.)">mobile</a> <b><a href="http://stackoverflow.&lt. </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.stackoverflow. </script> <noscript> &lt.get('/posts/337664/ivc/7ea7').downvotes)"> <div class="answer-votes answered-accepted default">0</div> </a> <a href="http://stackoverflow.ready(function(){$.img src="/posts/337664/ivc/7ea7" class="dno" alt="" width="0" height="0"&gt./div&gt.com/contact">contact us</a> </b> .com/q/16737810?rq=1" title="Vote score (upvotes downvotes)"> <div class="answer-votes answered-accepted default">1</div> </a> <a href="http://stackoverflow.div&gt.com/about/hiring">jobs</a> <a href="http://engine./questions/337664/counting-inversions-in-an-array/338252&quot.switchMobile(&quot.adzerk.com/">chat</a> <a href="http://data.&lt..com/legal">legal</a> <a href="http://stackexchange. &quot .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/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/">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= "WordPress developers and administrators">WordPress Answers</a></li> <li><a href="http://gis.com/" title="professiona l system and network administrators">Server Fault</a></li> <li><a href="http://superuser. ConTeXt.stackexchange.com/" title="p rofessional and independent game developers">Game Development</a></li> <li><a href="http://tex.com/" title="p ower users of web applications">Web Applications</a></li> <li><a href="http://askubuntu. and enthusias ts">Electrical Engineering</a></li> <li><a href="http://android. FreeBSD and other Un*x-like operating systems.com/" title ="pro webmasters">Webmasters</a></li> <li><a href="http://gamedev.stackexchange.LaTeX</a></li> </ol></td><td><ol> <li><a href="http://programmers.com/" title="carto graphers.stackexchange.com/" title="users of TeX.stackexchange.com/" title="Ubuntu users and developers">Ask Ubuntu</a></li> <li><a href="http://webmasters.com/" titl e="professional programmers interested in conceptual questions about software de velopment">Programmers</a></li> <li><a href="http://unix. geographers and GIS professionals">Geographic Information Systems</a>< /li> <li><a href="http://electronics.com/" title="professio nal and enthusiast programmers">Stack Overflow</a></li> <li><a href="http://serverfault.com/" title="computer enth usiasts and power users">Super User</a></li> <li><a href="http://webapps.com/" titl e="electronics and electrical engineering professionals.stackoverflow.stackexchange.stackexchange.stackexchange. Linux</a> </li> <li><a href="http://apple.stackexchange. and related typesetting systems">TeX .stackexchange.<b><a href="http://meta.stackexchange.">Unix &amp.com/" title="e nthusiasts and power users of the Android operating system">Android Enthusiasts< . LaTeX.stackexchange.com/" title="pow er users of Apple hardware and software">Ask Different (Apple)</a></li> <li><a href="http://wordpress. students.com/" title="user s of Linux.

com/" title=" scientific skepticism">Skeptics</a></li> <li><a href="http://judaism.com/" title="sci ence fiction and fantasy enthusiasts">Science Fiction &amp.stackexchange.com/sites#technology" class="more"> more (13) </a> </li> </ol> </td> <td> <ol> <li><a href="http://photo.com/" title="pro fessional.stackexchange.com/" title=" IT security professionals">IT Security</a></li> </ol></td><td><ol> <li><a href="http://dba.com/" titl e="users of Mathematica">Mathematica</a></li> <li> <a href="http://stackexchange. enthusiast and amateur photographers">Photography</a></li> <li><a href="http://scifi.stackexchange.com/" title="ro ad warriors and seasoned travelers">Travel</a></li> <li><a href="http://christianity.stackexchange.stackexchange. Fantasy</a></li> <li><a href="http://cooking.com/" title ="SharePoint enthusiasts">SharePoint</a></li> <li><a href="http://ux.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./a></li> <li><a href="http://security.com/" title="l inguists.com/" title="p rofessional and amateur chefs">Seasoned Advice (cooking)</a></li> <li><a href="http://diy.com/" title="Dr upal developers and administrators">Drupal Answers</a></li> <li><a href="http://sharepoint.stackexchange.stackexchange.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. experts in Christianity and those interested in learni ng more">Christianity</a></li> <li><a href="http://gaming.stackexchange. etymologists.stackexchange.com/" title="pa ssionate videogamers on all platforms">Arqade (gaming)</a></li> .com/" title="user e xperience researchers and experts">User Experience</a></li> <li><a href="http://mathematica.com/" title="contr actors and serious DIYers">Home Improvement</a></li> <li> <a href="http://stackexchange.stackexchange.stackexchange. and serious English language enthusiasts">English Langua ge &amp.com/" tit le="committed Christians.stackexchange.com/sites#lifearts" cl ass="more"> more (13) </a> </li> </ol> </td> <td> <ol> <li><a href="http://english. Usage</a></li> <li><a href="http://skeptics.stackexchange.stackexchange.

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

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