Problem Summary
Given an array of N integers, calculate the number of swaps you need to perfom to sort the array in ascending order. You can only swap adjacent elements.
Solution
We use merge sort to solve this problem. During each merging process, we count the number of swaps. And we get the sum recursively.
Note that we can only swap adjacent elements. So moving an integer from position j to position i requires i-j swaps.
A trick for saving time :
We can use two arrays A and B, to store the data, and if this time we perfom the merge function from A to B, the next time we perfom it from B to A. In this way we do not have to copy the array every time.
Code
|
|