views:

125

answers:

1

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
+3  A: 

Your binary search is not right.

You shouldn't compare i with j, you should compare the sum. Also, it is easier if you binary search for 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

Also, you keep overwriting m in your main function. You need something like this:

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]   

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 to n - 1 for the same reason.

IVlad
thanks |V|ad but I think for the first if part in the binary search we will check it in the **If (arr[j] = x - arr[i]) Return arr[j] **isn't?
That part checks if there's a solution. You must also check if you have a one-element subarray: if yes, check if that element is the solution. Even if it is a solution or isn't, you must break out of the recursion, otherwise you have an infinite loop.
IVlad
aha I get it ,thanks a lot :)