Problem description: The sorted (ascending) array is a [n] to find out whether there are two numbers in the array and the given X
Solution:
(1) define the pointer P = A [0], r = A [n-1]
(2) determine whether P + R is equal to X:
If the value is equal
If P + r> X, r moves forward to a grid.
If P + r <X, p moves one bit back.
(3) Repeat (2) until it is found or P> r stops
I used python to simulate why I used python. Today I see a sentence: Life is too short, use python!
Import randomr = int (raw_input ("input the sum x:") n = int (raw_input ("input the length N of the arry :")) arry = [] For I in range (1, n + 1): S = random. randint (1,100) Arry. append (s) Arry. sort () print arryprint ''x = 0y = n-1flag = truetimes = 0 while x <= Y: If arry [x] + arry [y] = R: print 'Arry [', X,']: ', arry [X],' + arry [', Y,']: ', arry [Y],' = ', r, ', Times =', times flag = false break Elif arry [x] + arry [y]> r: Y = Y-1 times = times + 1 else: X = x + 1 times = times + 1if flag: Print 'no two num \'s sum is the ', R