Find two numbers whose sum is equal to a given number in sorted array

In order to find the sum of the two array elements you need to traverse in array and check the sum of each element.

Let’s take an example of below sorted array in which we have to perform below iteration to find the sum of the array element.

[1, 5, 6, 8, 10]

First Iteration:

1 5
1 6
1 8
1 10

Second Iteration:
5 6
5 8
5 10

Third Iteration:
6 8
6 10

Fourth Iteration:
8 10

If given sum is 13 then you will have to write a python program to print array elements 5 and 8.

a = [1, 5, 6, 8, 10]
l = len(a)
sum = 13
for i in range(l):
 for j in range(i+1 ,l):
     #print(a[i],a[j])
     sum1 = a[i] + a[j]
     if (sum1 == sum):
       print(" array elements are {} {}".format(a[i],a[j]))

Output:
array elements are 5 8

As array is sorted so you can compare first and last elements of the array and do the compare if while loop to reduce the number of iteration to get the output.

a = [1, 5, 6, 8, 10]
r = len(a) - 1
l = 0
while not a[l] + a[r] == sum:
    if a[l] + a[r] > sum:
        r -=1
    else:
        l += 1
    print
print(" array elements are {} {}".format(a[l],a[r]))
(Visited 284 times, 19 visits today)