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

被折叠的 条评论
为什么被折叠?



