With a binary indexed tree (aka Fenwik tree), we can add elements and calculate their prefix sums in O(log n) time. One way to solve your problem using it is the following:
(1) Calculate the permutation's inversion vector: traverse the array and for each index i and element v, first add (i - prefix sum 0 to v) to the results, then add 1 at index v in the tree. If you think about it, i equals the number of inversions we would count for i if all preceding elements were greater than i; so we subtract the number of elements less than v encountered so far, which is exactly the prefix sum up to index v in the tree so far. This operation takes time O(n * log n) For example,
Array: {1,5,4,6,2,0,3}
Traversal: (0-0)
(1-1)
(2-1)
...
Inversion vector: 0 0 1 0 3 5 3
(2) Now the fun part. Since we are allowed to rotate the sorted order, let's think what would happen if we moved the 6 in the target-sorted-order to the beginning: instead of zero, the 6 in our array would now count 3 inversions, a number equal to the count of elements preceding it; and each element following the 6 will have one inversion less since it would no longer need to be swapped with 6. Continue:
Array: {1,5,4,6,2,0,3}
Original vector: 0 0 1 0 3 5 3 (12)
V with 6 at start: 0,0,1,3,2,4,2 (12)
V with 5,6 at start: 0,1,0,2,1,3,1 (8)
V with 4,5,6 at start: 0,1,2,1,0,2,0 (6)
(3,4,5,6,0,1,2) 0,1,2,1,0,2,6 (12)
(2,3,4,5,6,0,1) 0,1,2,1,4,1,5 (14)
(1,2,3,4,5,6,0) 0,0,1,0,3,0,4 (8)
But this operation can take time O(n) if we simply use the elements' position in the array, which we can hash beforehand. Given original inversion vector 0 0 1 0 3 5 3, we repeatedly apply the following operation to its sum of 12 and choose the minimum:
12
+ 3 - 3 (=12) // + index of 6 - (n - index of 6 - 1)
+ 1 - 5 (=8) // + index of 5 - (n - index of 5 - 1)
+ 2 - 4 (=6) // ...
+ 6 - 0 (=12)
+ 4 - 2 (=14)
+ 0 - 6 (=8)
As we can see, the minimum swaps needed are 6 if we choose rotated target order (4,5,6,0,1,2,3):
Array: {1,5,4,6,2,0,3}
Target: {4,5,6,0,1,2,3}
# Swaps: 0 1 2 1 0 2 0
Swaps: 0,2
5,1
4,1
4,5
6,1
0,1
[1,3,5,2,4]be a solution, too? It consists of two sorted parts,[1,3,5]and[2,4], but from the link I think this is not legal, right?