For a given descending sequence, given an n. Find two numbers in the array so that their sum equals the given number. Requires a time complexity of O (n).
BOOL Findsumelements (int array[], int length, int sum, int *elem1, int *elem2) {if (length = 0) {return
False
}
int tempsum = 0; Record elem1 and ELEM2 values in the array in the lower ordinal number//elem1 from the first element, elem2 starting with the last element
int head = 0; int tail = length-1;
while (Head < tail) {TempSum = Array[head] + array[tail];
if (tempsum = = sum) {*elem1 = Array[head];
*ELEM2 = Array[tail];
return true;
}else if (TempSum > Sum) {--tail;
}else {++head;
return false; }
Ideas:
Because the array is sorted in ascending order, all subsequent values must be larger than the preceding values.
Set two variables elem1 and elem2,elem1 to start backwards from the first number of arrays, elem2 to move forward from the last number of arrays.
The and of two variables are compared with the given number:
When and greater than the given number, the ELEM2 step forward, continue to compare;
When and less than the given number, elem1 a step backward, continue to compare;
Returns the current two variable values when and equals the given number, exiting the lookup.