A function of two number and equal to one input value in an ordered array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.