How to add specific number of inversions to sorted array

Question

Given a sorted array, is there a way to insert a specific number of inversions (at random locations)? At first I thought this would be straightforward, but then realized inversions can "undo" each other. Consider:

starting with array: 2,4,6,8
one inversion: 4,2,6,8

now if you wanted to add another inversion (at random) you could end up with 4,2,8,6 which would be good or you could end up with 2,4,6,8 which would be bad as it is back to the original.

It also doesn't work removing an index after it has been used. For example 1,2,3 -> 3,2,1 if we excluded the first and last index then we miss out on the permutation 3,1,2 so this approach doesn't work.

It doesn't have to be an array. It could be a list or other structure.

Any suggestions on algorithms to look into?


Show source
| sorting   | arrays   | permutation   | algorithm   | language-agnostic   2016-10-24 07:10 1 Answers

Answers ( 1 )

  1. 2016-10-24 09:10
    Number of inversions in an array is -
    
    For a given array a[n]
    
        An inversion is -
        if a[i] > a[j] such that i<j
    Also,
    
        Max number of inversions = n*(n-1)/2 
        where n is the size of array
    
    Now use this algorithm , Inversion with count k
    
        0. Sort the array in ascending order
        1. Find greatest l, such that l(l-1)/2 < k
        2. Take first l smallest numbers and arrange in descending order.
        3. Compute m = k - l(l-1)/2
        4. Place the (l+1)th smallest number and place it at (l-m + 1)th
     position, shifting others by one place to the right.
    
    Example : 
    arr = [1,2,3,4,5]
    Inversion = 8
    l = 4 , as 4*3/2 = 6
    m = 8 - 6 = 2
    
    So,
    
        0. Sorting the array => [1,2,3,4,5]
        1. l = 4
        2. 4 3 2 1 5
        3. m = 2
        4. Placing 5 at 3rd position, by shifting others one place to right => 4 3 5 2 1
    
    Hence your answer become 4 3 5 2 1
    
◀ Go back