{"id":25835,"date":"2017-05-30T20:41:14","date_gmt":"2017-05-30T15:11:14","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25835"},"modified":"2018-10-29T11:40:10","modified_gmt":"2018-10-29T06:10:10","slug":"java-programming-count-inversions-in-an-array","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-count-inversions-in-an-array\/","title":{"rendered":"Count Inversions in an array"},"content":{"rendered":"<p><strong>Count Inversions<\/strong> in an <a href=\"https:\/\/www.wikitechy.com\/technology\/algorithm-in-c-median-of-two-sorted-arrays\/\">array <\/a>indicates &#8211; how far (or close) the array is from being sorted. If array is already <a href=\"https:\/\/www.wikitechy.com\/technology\/sorted-insert-circular-linked-list-2\/\" target=\"_blank\" rel=\"noopener\">sorted<\/a> then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.<\/p>\n<p><span id=\"more-3968\"><\/span>Formally speaking, two elements a[i] and a[j] form an inversion if a[i] &gt; a[j] and i &lt; j<\/p>\n<h4 id=\"example\"><span style=\"color: #993300;\"><strong>Example:<\/strong><\/span><\/h4>\n<p>The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3)<\/p>\n<h3 id=\"method-1-simple\"><span style=\"color: #003366;\"><strong>METHOD 1 (Simple)<\/strong><\/span><\/h3>\n<p>For each element, count number of elements which are on right side of it and are smaller than it.<\/p>\n[ad type=&#8221;banner&#8221;]\n<h3 id=\"implementation\"><span style=\"color: #000080;\"><strong>Implementation:<\/strong><\/span><\/h3>\n<h3 id=\"java-programming-for-count-inversions-in-an-array\"><span style=\"color: #339966;\"><b>Java Programming for Count Inversions in an array:\u00a0<\/b><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class Test<br\/>{<br\/>    static int arr[] = new int[]{1, 20, 6, 4, 5};<br\/>     <br\/>    static int getInvCount(int n)<br\/>    {<br\/>      int inv_count = 0;<br\/>      for (int i = 0; i &lt; n - 1; i++)<br\/>        for (int j = i+1; j &lt; n; j++)<br\/>          if (arr[i] &gt; arr[j])<br\/>            inv_count++;<br\/>      <br\/>      return inv_count;<br\/>    }<br\/>  <br\/>    public static void main(String[] args) <br\/>    {<br\/>        System.out.println(&quot;Number of inversions are &quot; + getInvCount(arr.length));<br\/>     <br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<div class=\"responsive-tabs-wrapper\">\n<h3 id=\"output\"><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>Number of inversions are 5<\/pre>\n<p><span style=\"color: #993366;\"><strong>Time Complexity:<\/strong><\/span> <strong>O(n^2)<\/strong><\/p>\n<h3 id=\"method-2enhance-merge-sort\"><span style=\"color: #000080;\"><strong>METHOD 2(Enhance Merge Sort)<\/strong><\/span><\/h3>\n<p>Suppose we know the number of inversions in the left half and right half of the array (let be<em><strong> inv1 and inv2<\/strong><\/em>), what kinds of inversions are not accounted for in Inv1 + Inv2? The answer is \u2013 the inversions we have to count during the merge step. Therefore, to get number of inversions, we need to add number of inversions in left subarray, right subarray and <a href=\"https:\/\/www.wikitechy.com\/tutorials\/java\/merge-sort-algorithm-in-java\" target=\"_blank\" rel=\"noopener\">merge( )<\/a>.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-25855\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array.png\" alt=\"Count Inversions in an array\" width=\"576\" height=\"289\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array.png 576w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-300x151.png 300w\" sizes=\"(max-width: 576px) 100vw, 576px\" \/><\/p>\n<h3 id=\"how-to-get-number-of-inversions-in-merge\"><span style=\"color: #ff6600;\"><strong>How to get number of inversions in merge()?<\/strong><\/span><\/h3>\n[ad type=&#8221;banner&#8221;]\n<p>In <a href=\"https:\/\/www.wikitechy.com\/technology\/java-programming-merge-sort-doubly-linked-list\/\" target=\"_blank\" rel=\"noopener\">merge<\/a> process, let i is used for indexing left <a href=\"https:\/\/www.wikitechy.com\/technology\/java-programming-length-largest-subarray-contiguous-elements-2\/\" target=\"_blank\" rel=\"noopener\">sub-array<\/a> and j for right sub-array. At any step in merge(), if a[i] is greater than a[j], then there are (mid \u2013 i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] \u2026 a[mid]) will be greater than a[j]\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26089\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-1.png\" alt=\"Count Inversions in an array\" width=\"562\" height=\"275\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-1.png 562w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-1-300x147.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-1-559x275.png 559w\" sizes=\"(max-width: 562px) 100vw, 562px\" \/><\/p>\n<h3 id=\"the-complete-picture\"><span style=\"color: #ff9900;\"><strong>The complete picture:<\/strong><\/span><\/h3>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26088\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-java.png\" alt=\"Count Inversions in an array java\" width=\"631\" height=\"502\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-java.png 631w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Count-Inversions-in-an-array-java-300x239.png 300w\" sizes=\"(max-width: 631px) 100vw, 631px\" \/><\/p>\n<h3 id=\"implementation-2\"><span style=\"color: #000080;\"><strong>Implementation:<\/strong><\/span><\/h3>\n<h3 id=\"java-programming-for-count-inversions-in-an-array-2\"><span style=\"color: #339966;\"><b>Java Programming for Count Inversions in an array:\u00a0<\/b><\/span><\/h3>\n[ad type=&#8221;banner&#8221;]\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\"> \/\/ Java implementation of counting the <br\/>\/\/ inversion using merge sort<br\/> <br\/>class Test<br\/>{<br\/>     <br\/>  <br\/>    static int mergeSort(int arr[], int array_size)<br\/>    {<br\/>        int temp[] = new int[array_size];<br\/>        return _mergeSort(arr, temp, 0, array_size - 1);<br\/>    }<br\/>      <br\/>   <br\/>    static int _mergeSort(int arr[], int temp[], int left, int right)<br\/>    {<br\/>      int mid, inv_count = 0;<br\/>      if (right &gt; left)<br\/>      {<br\/>        <br\/>        mid = (right + left)\/2;<br\/>      <br\/>        inv_count  = _mergeSort(arr, temp, left, mid);<br\/>        inv_count += _mergeSort(arr, temp, mid+1, right);<br\/>      <br\/><br\/>        inv_count += merge(arr, temp, left, mid+1, right);<br\/>      }<br\/>      return inv_count;<br\/>    }<br\/>      <br\/>    <br\/>    static int merge(int arr[], int temp[], int left, int mid, int right)<br\/>    {<br\/>      int i, j, k;<br\/>      int inv_count = 0;<br\/>      <br\/>      i = left; <br\/>      j = mid;  <br\/>      k = left; <br\/>      while ((i &lt;= mid - 1) &amp;&amp; (j &lt;= right))<br\/>      {<br\/>        if (arr[i] &lt;= arr[j])<br\/>        {<br\/>          temp[k++] = arr[i++];<br\/>        }<br\/>        else<br\/>        {<br\/>          temp[k++] = arr[j++];<br\/>      <br\/>         <br\/>          inv_count = inv_count + (mid - i);<br\/>        }<br\/>      }<br\/>      <br\/>      <br\/>      while (i &lt;= mid - 1)<br\/>        temp[k++] = arr[i++];<br\/>      <br\/>      <br\/>      while (j &lt;= right)<br\/>        temp[k++] = arr[j++];<br\/>      <br\/>      <br\/>      for (i=left; i &lt;= right; i++)<br\/>        arr[i] = temp[i];<br\/>      <br\/>      return inv_count;<br\/>    }<br\/>  <br\/><br\/>    public static void main(String[] args) <br\/>    {<br\/>        int arr[] = new int[]{1, 20, 6, 4, 5};<br\/>        System.out.println(&quot;Number of inversions are &quot; + mergeSort(arr, 5));<br\/>         }<br\/>}<\/code><\/pre> <\/div>\n<h3 id=\"output-2\"><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>Number of inversions are 5<\/pre>\n<p>If we want to count only inversions then we need to create a copy of original array and call <strong>mergeSort()<\/strong> on copy.<br \/>\n<strong><br \/>\n<span style=\"color: #993366;\">Time Complexity:<\/span> O(nlogn)<\/strong><\/p>\n<p><span style=\"color: #993366;\"><strong>Algorithmic Paradigm:\u00a0<\/strong><\/span><span style=\"color: #3366ff;\"><a style=\"color: #3366ff;\" href=\"https:\/\/www.wikitechy.com\/technology\/algorithm-in-c-median-of-two-sorted-arrays\/\" target=\"_blank\" rel=\"noopener\"><strong>Divide and Conquer<\/strong><\/a><\/span><\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Java Programming-Count Inversions in an array-Divide and Conquer-Inversion Count for an array indicates how far (or close) the array is from being sorted.<\/p>\n","protected":false},"author":1,"featured_media":26089,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73719],"tags":[75860,75867,75866,75865,75859,75864,75876,75861,75863,75862,75877],"class_list":["post-25835","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-divide-and-conquer","tag-count-inversions-in-an-array-java","tag-count-inversions-in-matrix","tag-count-inversions-python","tag-counting-inversions-c","tag-counting-inversions-divide-and-conquer","tag-counting-inversions-divide-and-conquer-algorithm","tag-counting-inversions-python","tag-inversion-count-using-bit","tag-maximum-number-of-inversions-in-an-array","tag-write-a-c-program-to-find-the-inversion-count-of-an-array","tag-write-a-program-to-find-the-inversion-count-of-an-array-in-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25835","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25835"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25835\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/26089"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25835"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25835"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25835"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}