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
Your binary search is not right.
You shouldn’t compare
iwithj, you should compare the sum. Also, it is easier if you binary search forx - arr[i].Also, you keep overwriting
min 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_SOLUTIONbecause there’s nothing to group the last element with. Also, you only need to go up ton - 1for the same reason.