用 Θ(nlogn) 编写算法
我自己写了这段代码(这不是家庭作业)我想知道这是正确的吗?感谢
时间为 θ (nlogn) 的算法,它可以提供一个包含 n 个成员的数组来确定数组中的两个元素是否是等于 x 然后返回这些元素
Algorithm Sum(arr,1,n):
MergeSort(arr)
For i<-- 1 to n
m<-- BinarySearch(arr,arr[i],i+1,n)
return m and arr[i]
//end of the sum algorithm
Algorithm BinarySearch(arr,arr[i],p,q)
J<--[p+q/2]
If (arr[j]+arr[i]=x)
Return arr[j]
else if (i<j)
Return BinarySearch(arr,arr[i],p,j-1)
else
Return BinarySearch(arr,arr[i-j],j+1,q)
// end of BinarySearch algorithm
I have written this code for myself(it is not a home work) I want to know is this correct?thanks
Algorithm with time Θ (nlogn), which can provide an array of n members to determine whether two elements in the array that are equal to x and then return those elements
Algorithm Sum(arr,1,n):
MergeSort(arr)
For i<-- 1 to n
m<-- BinarySearch(arr,arr[i],i+1,n)
return m and arr[i]
//end of the sum algorithm
Algorithm BinarySearch(arr,arr[i],p,q)
J<--[p+q/2]
If (arr[j]+arr[i]=x)
Return arr[j]
else if (i<j)
Return BinarySearch(arr,arr[i],p,j-1)
else
Return BinarySearch(arr,arr[i-j],j+1,q)
// end of BinarySearch algorithm
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的二分查找是不正确的。
您不应该将
i
与j
进行比较,而应该比较总和。另外,如果您对x - arr[i]
进行二分搜索,会更容易。另外,您不断在主函数中覆盖
m
。你需要这样的东西:这可以确保你在找到解决方案后停止。在您的情况下,算法将始终返回
NO_SOLUTION
因为没有任何内容可以将最后一个元素分组。此外,出于同样的原因,您只需要上升到n - 1
即可。Your binary search is not right.
You shouldn't compare
i
withj
, you should compare the sum. Also, it is easier if you binary search forx - arr[i]
.Also, you keep overwriting
m
in your main function. You need something like this:This makes sure you stop after you found a solution. In your case, the algorithm would always return
NO_SOLUTION
because there's nothing to group the last element with. Also, you only need to go up ton - 1
for the same reason.