walkccc / CLRS

📚 Solutions to Introduction to Algorithms Third Edition
https://walkccc.me/CLRS
MIT License
4.63k stars 1.26k forks source link

Exercise 2.3-7 #456

Open IgorSuharev opened 2 years ago

IgorSuharev commented 2 years ago

After sorting of S, a search of two a, b in S such that a + b = x can be improved.

FIND-SUM(S, x) // Indexes in S are 1, 2, ..., n
S = SORT(S)
i = 1
j = n
while i < j
    sum = S[i] + S[j]
    if sum == x
        return TRUE
    if sum < x
        i = i + 1
    else
        j = j - 1
return FALSE

Using this way, the time complexity of the search is Θ(n) instead of Θ(n lgn). (But, it's obviously that time complexity of entire algorithm stays same.)

funny1dog commented 1 year ago

Yes, you are right, but the final time complexity stays the same.