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.
The only tricky part here is how to merge two sorted arrays. Here is my similar solution. Might be slightly easier to understand because of less number of arguments. Though, I recommend to think as much as you can before looking into the solution. :
publicstaticlongcountInversions(int[]arr){returnmergeSort(arr,0,arr.length-1);}publicstaticlongmergeSort(int[]arr,intstart,intend){if(start==end)return0;intmid=(start+end)/2;longcount=0;count+=mergeSort(arr,start,mid);//left inversionscount+=mergeSort(arr,mid+1,end);//right inversionscount+=merge(arr,start,end);// split inversions.returncount;}publicstaticlongmerge(int[]arr,intstart,intend){intmid=(start+end)/2;int[]newArr=newint[end-start+1];intcurr=0;inti=start;intj=mid+1;longcount=0;while(i<=mid&&j<=end){if(arr[i]>arr[j]){newArr[curr++]=arr[j++];count+=mid-i+1;// Tricky part.}elsenewArr[curr++]=arr[i++];}// Leftover elements here.while(i<=mid){newArr[curr++]=arr[i++];}while(j<=end){newArr[curr++]=arr[j++];}System.arraycopy(newArr,0,arr,start,end-start+1);// Usual stuff from merge sort algorithm with arrays.returncount;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Merge Sort: Counting Inversions
You are viewing a single comment's thread. Return to all comments →
The only tricky part here is how to merge two sorted arrays. Here is my similar solution. Might be slightly easier to understand because of less number of arguments. Though, I recommend to think as much as you can before looking into the solution. :