Analysis of algorithm time complexity—taking finding the two closest numbers in a sequence as an example

        Programming is not just about software architecture and object-oriented design. Algorithm design is also an aspect it needs to solve. A good algorithm can usually solve a complex problem in the shortest time. Here, use Python to compare the differences between two simple algorithms.

        Suppose we now want to find the two numbers from a list of numbers that are closest to each other but not equal, that is, find the two numbers with the smallest absolute difference.

Algorithm 1:

from random import randrange
import time

t1=time.perf_counter()
seq=[randrange(10**10) for i in range(1000)]
dd=float("inf")
for x in seq:
    for y in seq:
        if x==y:
            continue
        d=abs(x-y)
        if d < dd:
            xx,yy,dd=x,y,d
t2=time.perf_counter()
print("Time:",t2-t1)

        Algorithm 1 has two levels of nested loops, each of which traverses seq, which is a square-level operation. When the sequence length of seq is 1000, the time spent is about 0.5s, and when the sequence length increases to 10000, the time spent is 48s. It can be seen that Algorithm 1 is not an ideal algorithm.

Algorithm 2:

from random import randrange
import time

t1=time.perf_counter()
seq=[randrange(10**10) for i in range(1000)]
seq.sort()
dd=float("inf")
for i in range(len(seq)-1):
    x,y=seq[i],seq[i+1]
    if x==y:
        continue
    d=abs(x-y)
    if d<dd:
        xx,yy,dd=x,y,d
t2=time.perf_counter()
print("Time:",t2-t1)

        Algorithm 2 uses Python's built-in sort method to sort the sequence seq. The two adjacent numbers in the sorted sequence must be the closest, so the absolute difference between the two adjacent numbers can be calculated in just one loop. Just compare. In this case, the time complexity is greatly reduced to the level of linear logarithmic operations. When the sequence length is 1000, the time consumed is 0.004s. When the sequence length increases to 10000, the time consumed is not enough 0.04s, which greatly improves the operation efficiency.

Guess you like

Origin blog.csdn.net/m0_56572447/article/details/126460968