We have an unsorted sequence of N numbers (1, 2, 3, 4, ... N). We can sort the whole sequence by swapping adjacent elements in a specific order. Given a sequence, how do I c
Thanks @Ivaylo Strandjev's explanation, to make the answer more complete, here is Java implementation:
// http://stackoverflow.com/questions/20990127/sorting-a-sequence-by-swapping-adjacent-elements-using-minimum-swaps
// The minimum number if swaps is equal to the number of inversions in the array
public static long sortWithSwap(int [] a) {
return invCount(a, 0, a.length-1);
}
private static long invCount(int[] a, int left, int right) {
if(left >= right) return 0;
int mid = left + (right-left)/2;
long cnt = invCount(a, left, mid) + invCount(a, mid+1, right);
cnt += merge(a, left, mid, right);
return cnt;
}
private static long merge(int[] a, int left, int mid, int right) {
long cnt = 0;
int i = left, j = mid+1, k = left;
int[] b = new int[a.length];
while(i<=mid && j<=right) {
if(a[i] <= a[j]) b[k++] = a[i++];
else {
b[k++] = a[j++];
cnt += mid - i + 1;
}
}
while(i <= mid) {
b[k++] = a[i++];
}
while(j <= right) {
b[k++] = a[j++];
}
for(i=left; i<=right; i++) a[i] = b[i];
return cnt;
}