Count inversions and sort