Algorithm 为什么分治反转计数n*log(n)?
我看过的很多资料都说分治反转计数法的运行时间是nlogn,但我不明白为什么。 我知道merge-sort有nlogn-time,因为每次我们需要合并两个数组时,直到基本情况为logn且合并运行时为n为止的分割数组的数量 但当我们在合并排序的基础上进行备份时,我们需要比较数组的两部分:Algorithm 为什么分治反转计数n*log(n)?,algorithm,sorting,Algorithm,Sorting,我看过的很多资料都说分治反转计数法的运行时间是nlogn,但我不明白为什么。 我知道merge-sort有nlogn-time,因为每次我们需要合并两个数组时,直到基本情况为logn且合并运行时为n为止的分割数组的数量 但当我们在合并排序的基础上进行备份时,我们需要比较数组的两部分: [a,b,c] and [d,e,f] 对于左数组中的所有元素,a需要与d、e和f最坏情况进行比较,以此类推。因此,似乎仅此一项就有n^2/4的运行时,那么分治反演算法的运行时不是n^2吗 [a,b,c]和[d
[a,b,c] and [d,e,f]
对于左数组中的所有元素,a需要与d、e和f最坏情况进行比较,以此类推。因此,似乎仅此一项就有n^2/4的运行时,那么分治反演算法的运行时不是n^2吗
[a,b,c]和[d,e,f]
a需要与d、e和f最坏情况进行比较
环路
while (not at end of A && not at end of B)
无论比较结果如何,始终有O | A |+B |步。合并和计数既没有最佳情况,也没有最坏情况
排序与计数
合并并计数A、B
if list L has one element
return (0, L)
Divide the list into two halves A and B
(rA, A) ← Sort-and-Count(A)
(rB, B) ← Sort-and-Count(B)
(rC, L) ← Merge-and-Count(A, B)
r = rA + rB + rC
return (r, L)
curA = 0; curB = 0;
count = 0;
mergedList = empty list
while (not at end of A && not at end of B)
a = A[curA]; b = B[curB];
if (a < b) // only one comparison
append a to mergedList;
curA++;
else
append b to mergedList;
curB++;
count = count + num elements left in A
if (at end of A)
append rest of B to mergedList;
else
append rest of A to mergedList;
return (count, mergedList);