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 those who attempt to implement Insertion sort, don't. This is the brute force method of what should be done, you only need to find a way to do it in N log N time. This is to actually count the inversions while merge sorting. A hint: when merging two subarrays, when taking an element of the right half, the number of inversions that it has is the number of elements still notm erged from the left half.
public static long count(int[] a) {
long inversions = 0;
for (int i = 0; i < a.length; i++)
for (int j = i; j < a.length; j++)
if (a[i] > a[j])
inversions++;
return inversions;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insertion Sort Advanced Analysis
You are viewing a single comment's thread. Return to all comments →
For those who attempt to implement Insertion sort, don't. This is the brute force method of what should be done, you only need to find a way to do it in N log N time. This is to actually count the inversions while merge sorting. A hint: when merging two subarrays, when taking an element of the right half, the number of inversions that it has is the number of elements still notm erged from the left half.