Insertion Sort Advanced Analysis(逆序对)

来源:互联网 发布:2015年度十大网络用语 编辑:程序博客网 时间:2024/06/05 16:58

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 3Moves:   -        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 countdef 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 countn = 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)


0 0
原创粉丝点击