Topic:
Enter an array and a number that have been sorted in ascending order, and find two numbers in the array so that they are exactly the number entered. Requires a time complexity of O (N).
If there are many pairs of numbers and equals the input number, the output can be any pair.
For example, the input array 1,2,4,7,11,15 and the number 15, because of 4+11=15, so output 4 and 11.
The code is as follows:
/*data[] is an ordered array,
Length of the array
sum for the user input and
NUM1 is the first number that matches and equals sum
Num2 is the second number */
#include <iostream>
using namespace Std;
BOOL Findtwonumberswithsum (int data[], unsigned int length, int sum, int& num1, int& num2)
{
BOOL found = false;
if (length < 1)
return found;
int begin = 0;
int end = Length-1;
while (End > Begin)
{
Long cursum = Data[begin] + data[end];
if (cursum = = SUM)
{
NUM1 = Data[begin];
num2 = Data[end];
Found = true;
Break
}
else if (cursum > Sum)
end--;
else begin++;
}
return found;
}
int main ()
{
int x, y;
int a[6] = {1, 2, 4, 7, 11, 15};
if (Findtwonumberswithsum (A, 6, X, y))
{
cout << x << endl << y<< Endl;
}
return 0;
}
A function of two number and equal to one input value in an ordered array