如何向已排序的数组添加特定数量的反转

时间:2016-10-24 05:46:32

标签: arrays algorithm sorting language-agnostic permutation

给定一个排序数组,有没有办法插入特定数量的反转(在随机位置)?起初我认为这将是直截了当的,但后来意识到反转可以"撤消"彼此。考虑:

从数组开始:2,4,6,8
一次倒置:4,2,6,8

现在如果你想添加另一个反转(随机)你最终会得到4,2,8,6这样会很好,或者你最终会得到2,4,6,8这样会很糟糕,因为它又恢复原状了。

在使用索引后,它也无法删除索引。例如 1,2,3 - > 3,2,1如果我们排除了第一个和最后一个索引,那么我们会错过排列3,1,2,所以这种方法不起作用。

它不一定是一个数组。它可以是列表或其他结构。

有关算法的任何建议吗?

1 个答案:

答案 0 :(得分:2)

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