为了账号安全,请及时绑定邮箱和手机立即绑定

计数反转算法中的错误

计数反转算法中的错误

HUWWW 2023-03-16 16:08:41
我正在尝试编写一种算法来计算数组中的反转次数。反转是 A[i] > A[j] 和 i < j。def sort_and_count(L):    if len(L)<2:        return 0, L    else:        A = L[:len(L)//2]        B = L[len(L)//2:]        rA, A = sort_and_count(A)        rB, B = sort_and_count(B)        r, L = merge_and_count(A,B)    return r+rB+rA, Ldef merge_and_count(A,B):    i = j = 0    count = 0    L = []    while len(A) > i and len(B) > j:        if A[i] <= B[j]:            L.append(A[i])            i+=1        else:            L.append(B[j])            count = count + (len(A)-1)            j+=1    #copy the remaining elements    for index in range(i,len(A)):        L.append(A[index])    for index in range(j,len(B)):        L.append(B[index])    return count, Lsort_and_count(A)[0]算法不正确。对于这个输入 A = [7, 3, 20, 16, 5, 8] 它返回 6。正确答案是 7 (7, 3),(7, 5),(20, 16),(20, 5) ,(20, 8),(16, 5),(16, 8)。对于某些输入,答案是正确的。我不确定是什么原因造成的。
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

我希望我知道它给出正确结果的输入是什么。你有一个错字:len(A) - 1应该是len(A) - i



查看完整回答
反对 回复 2023-03-16
  • 1 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号