Insertion Sort Advanced Analysis(逆序对)

本文介绍了一种计算插入排序过程中元素移位次数的方法,并提供了一个具体的算法实现。通过输入一组待排序的数据,该算法可以返回整个排序过程中所需的总移位次数。

Insertion Sort is a simple sorting technique which was covered in previous challenges. Sometimes, arrays may be too large for us to wait around for insertion sort to finish. Is there some other way we can calculate the number of times Insertion Sort shifts each elements when sorting an array?

If ki is the number of elements over which ith element of the array has to shift then total number of shift will be k1 + k2 + … + kN.

Input:
The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1],a[2]…,a[N].

Output:
Output T lines, containing the required answer for each test case.

Constraints:
1 <= T <= 5
1 <= N <= 100000
1 <= a[i] <= 1000000

Sample Input:

2  
5  
1 1 1 2 2  
5  
2 1 3 1 2

Sample Output:

0  
4   

Explanation
First test case is already sorted therefore there’s no need to shift any element. In second case it will proceed in following way.

Array: 2 1 3 1 2 -> 1 2 3 1 2 -> 1 1 2 3 2 -> 1 1 2 2 3
Moves:   -        1       -    2         -  1            = 4
def merge(a1, n1, a2, n2, a, n):
    c = c1 = c2 =0
    count = 0
    while c < n:
        if c1 == n1:
            while c < n:
                a[c] = a2[c2]
                c = c + 1
                c2 = c2 + 1
        elif c2 == n2:
            while c < n:
                a[c] = a1[c1]
                c = c + 1
                c1 = c1 + 1
        else:
            if a1[c1] > a2[c2]:
                a[c] = a2[c2]
                count = count + n1 - c1
                c = c + 1
                c2 = c2 + 1
            else:
                a[c] = a1[c1]
                c = c + 1
                c1 = c1 + 1
    return count

def Sort(a):
    n = len(a)
    if n == 1: return 0
    n1 = n/2
    n2 = n - n1
    a1 = a[:n1]
    a2 = a[n1:]
    count1 = Sort(a1)
    count2 = Sort(a2)
    c = c1 = c2 = 0
    count = count1 + count2 + merge(a1, n1, a2, n2, a, n)
    return count

n = input()
for iterate in range( n ):
    x = input()
    a = [ int( i ) for i in raw_input().strip().split() ]
    num = 0
    # Write code to compute answer using x, a and answer
    
    print Sort(a)


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值