3
$\begingroup$

Given an array $A$ with $n$ integers in it, one way of measuring the distance of the array from a sorted array is by counting inversions. A pair of indices $i,j ∈ {0,...,n−1}$ is called an inversion if $i < j$ and $A[i] > A[j]$. If the number of inversions is $k$ is it possible to sort the array in $θ(n + k)$ steps?

I tried going with the approach of bubble sort, but I couldn't go ahead with it. Also, if I figure out which sorting technique to use, it would definitely help me out, I guess. Any help is appreciated, thanks.

$\endgroup$
3
  • $\begingroup$ You would need to figure out the number of inversions ahead of time, and this will add to the complexity $\endgroup$
    – gd1035
    Commented Nov 14, 2018 at 17:25
  • $\begingroup$ Does "step" here mean a swap operation, whereas we have all time of the world to investigate the set of inversions? $\endgroup$ Commented Nov 14, 2018 at 17:36
  • $\begingroup$ @gd1035, but if I am understanding the problem we are given this. That is we know there to be to $k$ inversions and now we need to consider the time-complexity of a subroutine that is given this $k$ and needs to sort the array. $\endgroup$
    – Mason
    Commented Nov 14, 2018 at 17:50

1 Answer 1

1
$\begingroup$

What about the following algorithm.

Let's start with $A[0]$ and compare it with the following element. If next element is larger - move forward: compare $A[1]$ and $A[2]$. The part of the array behind us is sorted. If at some step we found $A[m] > A[m+1]$ - remember current position, swap the two elements. The number of inversions decreases by 1. Now we would need to check the previous pair, if it is inverted, swap them, and so on. Each step decreases number of inversions by 1. As soon as the previous pair is not inverted we can return to the remembered position: the part of array up to remembered position is sorted.

So, there are two types of steps: first type moves remembered position forward by one element, second type swaps two elements in the part of array up to the remembered position.

We will have to make exactly $n$ operations of the first type and exactly $k$ operations of the second type (because swap of two adjacent elements decreases the number of inversions exactly by one). So, the complexity of this algorithm is $θ(n + k)$.

I guess this is bubble sort.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .