Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 用Θ编写算法;(nlogn)_Algorithm_Analysis - Fatal编程技术网

Algorithm 用Θ编写算法;(nlogn)

Algorithm 用Θ编写算法;(nlogn),algorithm,analysis,Algorithm,Analysis,我已经为自己写了这段代码(这不是家庭作业),我想知道这是正确的吗?谢谢 带有时间Θ(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 Al

我已经为自己写了这段代码(这不是家庭作业),我想知道这是正确的吗?谢谢

带有时间Θ(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
算法和(arr,1,n):
合并排序(arr)

因为i你的二进制搜索是不对的

你不应该比较
i
j
,你应该比较总和。此外,如果您对
x-arr[i]
进行二进制搜索,则会更容易

Algorithm BinarySearch(arr,arr[i],p,q)
if (p == q)
    if (arr[p] == x - arr[i])
        return p
    else
        return NO_SOLUTION
j<--[(p+q)/2] // you forgot parentheses
If (arr[j] = x - arr[i]) 
       Return arr[j] 
else if (arr[j] > x - arr[i]) // our number is too big, restrict the search to smaller numbers
       Return BinarySearch(arr,arr[i],p,j)
else 
       Return BinarySearch(arr,arr[i],j+1,q) // arr[i] doesn't change

这确保您在找到解决方案后停止。在您的情况下,算法将始终返回
NO_SOLUTION
,因为没有可用于分组最后一个元素的内容。此外,出于同样的原因,您只需要转到
n-1

谢谢| V | ad,但我认为对于二进制搜索中的第一个if部分,我们将在**if(arr[j]=x-arr[I])返回arr[j]**is not中检查它是否有解决方案。还必须检查是否有一个元素子阵列:如果有,请检查该元素是否为解决方案。即使它是一个解决方案或不是,你必须打破递归,否则你会有一个无限循环。@Justin L:似乎有一个新的电流,所以,你会毫无理由地获得否决票:/真烦人!
Algorithm Sum(arr,1,n):
MergeSort(arr)
m = NO_SOLUTION
For i<-- 1 to n - 1
    if (m = NO_SOLUTION)
        m<-- BinarySearch(arr,arr[i],i+1,n)
    else
        break;

if (m = NO_SOLUTION)
    return NO_SOLUTION
else
    return m and arr[i]