Sword Point 41st: And two numbers for S: Enter an array of ascending order and a number, and find two numbers in the array so that their sum is exactly equal to S. If there are many pairs, output any pair can
1 //============================================================================2 //Name:jz-c-41.cpp3 //Author:laughing_lz4 //Version:5 //Copyright:all Right Reserved6 //Description: And two numbers for s: Enter an incremented sorted array and a number to find two numbers in the array so that their sum is exactly equal to S. If there are many pairs, output any pair can7 //============================================================================8 9#include <iostream>Ten#include <stdio.h> One using namespacestd; A - BOOLFindnumberswithsum (intData[],intLengthintSumint* NUM1,int*num2) { - BOOLFound =false; the if(Length <1|| NUM1 = = NULL | | Num2 = =NULL) - returnfound; - - intAhead = Length-1; + intbehind =0; - + while(Ahead >behind) { A Long LongCursum = Data[ahead] +Data[behind]; at - if(Cursum = =sum) { -*NUM1 =Data[behind]; -*num2 =Data[ahead]; -Found =true; - Break; in}Else if(Cursum >sum) -ahead--; to Else +behind++; - } the * returnfound; $ }Panax Notoginseng - //==================== test Code ==================== the voidTest (Char* TestName,intData[],intLengthintSum, + BOOLExpectedreturn) { A if(TestName! =NULL) theprintf"%s begins:", testname); + - intnum1, num2; $ intresult = findnumberswithsum (data, length, Sum, &NUM1, &num2); $ if(Result = =Expectedreturn) { - if(Result) { - if(num1 + num2 = =sum) theprintf"Passed. \ n"); - ElseWuyiprintf"Failed. \ n"); the}Else -printf"Passed. \ n"); Wu}Else -printf"Failed. \ n"); About } $ - //existence and two numbers for s, these two digits in the middle of the array - voidTest1 () { - intData[] = {1,2,4,7, One, the }; ATest ("Test1", data,sizeof(data)/sizeof(int), the,true); + } the - //exists and is two digits for s, these two digits are located in the two segments of the array $ voidTest2 () { the intData[] = {1,2,4,7, One, - }; theTest ("Test2", data,sizeof(data)/sizeof(int), -,true); the } the - //two numbers that do not exist and are for S in voidTest3 () { the intData[] = {1,2,4,7, One, - }; theTest ("Test3", data,sizeof(data)/sizeof(int),Ten,false); About } the the //Robustness Testing the voidTest4 () { +Test ("Test4"Null0,0,false); - } the Bayi intMainintargcChar**argv) { the Test1 (); the Test2 (); - Test3 (); - Test4 (); the the return 0; the}
jz-c-41