We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Make sure you use a long instead of an int to avoid integer overflow.
I added a ton of comments below to help explain the code.
importjava.util.Scanner;importjava.util.Arrays;/* We basically implement MergeSort and 1) Add "swaps" counter and 1 line of code to count swaps when merging 2) Use "long" instead of "int" to avoid integer overflow Runtime: O(n log n) Space Complexity: O(n)*/publicclassSolution{privatestaticclassMergeSort{/* Our array has up to n = 100,000 elements. That means there may be O(n^2) swaps. n^2 is 10,000,000,000. A Java int has max value 2,147,483,647 so we use a long to avoid integer overflow */privatelongswaps=0;publiclongmergeSort(int[]array){int[]helper=newint[array.length];mergeSort(array,helper,0,array.length-1);returnswaps;}privatevoidmergeSort(int[]array,int[]helper,intstart,intend){if(start<end){intmid=(start+end)/2;mergeSort(array,helper,start,mid);mergeSort(array,helper,mid+1,end);merge(array,helper,start,mid,end);}}privatevoidmerge(int[]array,int[]helper,intstart,intmid,intend){/* Fill helper array with same elements as original array */for(inti=start;i<=end;i++){// notice "i" goes from "start" to "end", not "0" to "array.length"helper[i]=array[i];}intcurr=start;intleft=start;intright=mid+1;/* Loop through helper[] left and right halves and continuously copy smaller element to array[] */while(left<=mid&&right<=end){if(helper[left]<=helper[right]){array[curr++]=helper[left++];}else{/* Each time we choose element from right side, we count up how many elements it is less than from left side. This is equivalent to counting swaps. */swaps+=mid+1-left;array[curr++]=helper[right++];}}/* Copy remaining elements of left half. Right half elements are already in proper place */while(left<=mid){array[curr++]=helper[left++];}}}publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intt=in.nextInt();for(inta0=0;a0<t;a0++){intn=in.nextInt();intarr[]=newint[n];for(intarr_i=0;arr_i<n;arr_i++){arr[arr_i]=in.nextInt();}MergeSortms=newMergeSort();System.out.println(ms.mergeSort(arr));}}}
Merge Sort: Counting Inversions
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
I used MergeSort to count inversions.
Make sure you use a long instead of an int to avoid integer overflow.
I added a ton of comments below to help explain the code.
From my HackerRank Java solutions.