码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - Insertion Sort Advanced Analysis

时间:2015-03-18 06:27:46      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

"How many inverted pairs" - that usually ends up with MergeSort solution (of course there are other solutions out there)

def mergeSort(arr):
    if len(arr) == 1:
        return 0, arr
    
    mid = len(arr) // 2
    cnt1, arr1 = mergeSort(arr[:mid])
    cnt2, arr2 = mergeSort(arr[mid:])
    
    #
    ret = []    
    cnt = 0
    
    i = 0
    j = 0
    inx = 0
    while i < len(arr1) and j < len(arr2):
        if arr1[i] <= arr2[j]:
            ret.append(arr1[i])
            i += 1
        elif arr2[j] < arr1[i]:
            ret.append(arr2[j])
            cnt += len(arr1) - i        # arr2 -> arr1
            j += 1        
    while i < len(arr1):
        ret.append(arr1[i])
        i += 1
    while j < len(arr2):
        ret.append(arr2[j])        
        j += 1
    
    return cnt1 + cnt2 + cnt, ret

T = int(input())
for _ in range(0, T):
    n = int(input())
    arr = [int(i) for i in input().strip().split()]

    cnt, _ = mergeSort(arr)
    print (cnt)

HackerRank - Insertion Sort Advanced Analysis

标签:

原文地址:http://www.cnblogs.com/tonix/p/4346133.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!