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)
- Insertion Sort Advanced Analysis(逆序对)
- 【hackerrank】Insertion Sort Advanced Analysis
- 【hackerrank】Insertion Sort Advanced Analysis
- Pat(Advanced Level)Practice--1098( Insertion or Heap Sort)
- codeforces 362 C. Insertion Sort(树状数组,逆序数)
- Introduction: Analysis of Algorithms, Insertion Sort, Merge Sort
- HDU 5775 Bubble Sort(逆序对)
- HDU5775-Bubble Sort(逆序对)
- PAT (Advanced Level) Practise 1098 Insertion or Heap Sort (25)
- PAT(Advanced Level)1098. Insertion or Heap Sort
- PAT (Advanced Level) Practise 1098 Insertion or Heap Sort (25)
- 【PAT】【Advanced Level】1098. Insertion or Heap Sort (25)
- 插入排序(insertion sort)
- 插入排序(insertion sort)
- 插入排序(Insertion Sort)
- 插入排序(Insertion-sort)
- Insertion Sort List(medium)
- 插入排序(insertion sort)
- Qt on Android:QTableView不显示选中虚框
- 又见01背包
- 算法java实现--回溯法--圆排列问题--排列树
- myeclipse工作空间报错处理
- javaEE jspsmart 实现文件上传和下载
- Insertion Sort Advanced Analysis(逆序对)
- oracle 表空间与数据文件详细(一)
- (M)常用EXCEL工作薄函数和VBA函数
- Objective-c文件类型
- 每日算法之十二:Roman to Integer
- A Simple Introduction To Computer Networking
- 自动给tmux现场做简单的备胎
- java的版本
- MongoDB 索引