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.
For people looking for PHP solution. You can use the merge sort procedure to solve this
functioncountInversions($arr){$temp=array_fill(0,count($arr),0);returnmergeSort($arr,$temp,0,count($arr)-1);}functionmergeSort(&$arr,&$temp,$left,$right){$inversions=0;if($left<$right){$mid=(int)(($left+$right)/2);$inversions+=mergeSort($arr,$temp,$left,$mid);$inversions+=mergeSort($arr,$temp,$mid+1,$right);$inversions+=merge($arr,$temp,$left,$mid,$right);}return$inversions;}functionmerge(&$arr,&$temp,$left,$mid,$right){$i=$left;$j=$mid+1;$k=$left;$inversions=0;while($i<=$mid&&$j<=$right){if($arr[$i]<=$arr[$j]){$temp[$k++]=$arr[$i++];}else{$temp[$k++]=$arr[$j++];// Count inversions$inversions+=($mid-$i+1);}}while($i<=$mid){$temp[$k++]=$arr[$i++];}while($j<=$right){$temp[$k++]=$arr[$j++];}// Copy back the merged elements to the original arrayfor($i=$left;$i<=$right;$i++){$arr[$i]=$temp[$i];}return$inversions;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Join us
Create a HackerRank account
Be part of a 26 million-strong community of developers
Please signup or login in order to view this challenge
Merge Sort: Counting Inversions
You are viewing a single comment's thread. Return to all comments →
For people looking for PHP solution. You can use the merge sort procedure to solve this