arrays - 数组中的反转,我错了什么。请查看下面的数学/伪代码
问题描述
我一直在尝试为反转次数编写伪代码。
在这个例子中,我们的数组被称为长度为 n 的 mainArray。并假设 n 是偶数。
据我了解,当i<j, mainArray[i] > mainArray[j]
. 然后我们交换位置以便对此进行排序。
使用归并排序算法,一旦我们到达基本情况并开始合并两半(左半边和右半边),代码如下所示
let i = 0, j=0, k=0, inversions = 0
for k in range(0,n-1)
if left-half[i] < right-half[j]
mainArray[k] = left-half[i]
i+=1
else
mainArray[k] = right-half[j]
j+=1
//now at this point an inversion has occurred
//so from my understanding at this point there was only 1 swap? because the program
//skipped left-half[i] and proceeded to right-half[j]
// so my answer was **"Inversions = Inversions + 1"** incrementing by 1 Inversions wherever the **Else-Block is run**.
//but in the solution the correct answer is
Inversions = Inversions + {(n/2)-i}
这部分我没看懂?为什么假设 right-half[j] 与数组左半部分中的所有剩余元素交换位置。 我在这里缺少什么关键点?
任何帮助,将不胜感激。谢谢。
解决方案
回想一下,left-half
并且right-half
是排序的,所以如果i<j, left-half[i] > right-half[j]
这left-half[i+1..n/2] > right[j]
也暗示。所以我们计数Inversions + {(n/2)-i}
所有的反转,而不仅仅是一个。
推荐阅读
- visual-c++ - 为什么 [ebp-8] 是 Visual C++ 中第一个局部变量的位置?
- android - 是否可以将两个不同的应用程序上传到具有高度相似代码库的 Apple Store 和 Play Store?
- redirect - Laravel 重定向到带有参数的命名路由返回状态 200
- bash - 每天保留一个文件,一个 3 天和 1 周,并删除其他文件
- angular - 没有为作者字段触发角度表单验证
- c# - 如何从 OkObjectResult 获取动态属性
- github - 如何使用 Pygithub API 执行“拉”命令
- c# - 为什么这个 XPath 表达式适用于一个节点而不适用于另一个节点?
- angularjs - 如何使 $scope.$broadcast 在 Ipad 中工作?
- asp.net-core - 作为 Windows 服务部署的 .net core(2.2) Web 应用程序的访问日志路径是什么