Four search algorithms

Find algorithm

Linear search

Definition: It is to find whether a certain value exists in a set of data (list) and return the subscript of its storage location. The most important problem that the search algorithm needs to solve is how to approach the target value in the shortest time.
Linear search : it means that no method is used, and it is judged one by one directly from beginning to end. But because the violence is simple, there is no need for the list to be ordered.

def lineSearch(arr,num):
    flag = 0
    for i in range(len(arr)):
        if arr[i]==num:
            flag=1
            print("找到了,在第{}个位置".format(i+1))
    if flag==0:
        print("没有找到!")
    
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
lineSearch(arr,9000000-1)
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

Binary search

Binary search : You must ensure that the data being searched is ordered. Its search strategy is: first judge the intermediate value and compare it with the target value; if it is greater, then discard the smaller half of the data on the left; if less than, discard the larger half of the data on the right; if they are equal, it has been found. The time efficiency of binary search for ordered data is O (logn).

def binarySearch(arr,left,right,findVal):
    #定义一个数组储存下标,又可能存在多个相同元素
    resIndex = []
    #arr必须有序
    mid = int((left+right)/2)
    midVal = arr[mid]
    
    if left>right:
        return -1
    
    if findVal > midVal:
        return binarySearch(arr,mid+1,right,findVal)
    elif findVal<midVal:
        return binarySearch(arr,left,mid-1,findVal)
    else:
        temp = mid - 1
        while(True):#左边
            if temp>len(arr)-1 or arr[temp]!=findVal:
                break
            resIndex.append(temp+1)
            temp-=1
            
        resIndex.append(mid+1)#中间
        
        temp=mid+1
        while(True):#右边
            if temp<0 or arr[temp]!=findVal:
                break
            resIndex.append(temp+1)
            temp+=1
        return resIndex

print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
print("Index="+str(binarySearch(arr,0,len(arr),1)))
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

Interpolation lookup

Interpolation search : Interpolation search is partially improved on the basis of binary search, so it also needs to be ordered data is ordered. It improves the calculation method of middle = (left + right) / 2 directly for each binary search. Using the knowledge of mathematical analysis, the split point was changed to ** left + (right-left) * (int ((findVal-arr [left]) / (arr [right] -arr [left]))) **, However, before use, it is necessary to determine whether the target value is greater than the maximum value of the data or less than the minimum value of the data, otherwise there will be a risk of cross-border.

def insertSearch(arr,left,right,findVal):
    #定义一个数组储存下标,又可能存在多个相同元素
    resIndex = []
    #arr必须有序
   
    if left>right or findVal<arr[0] or findVal>arr[len(arr)-1]:
        return -1
    
    mid = left + (right-left)*(int((findVal-arr[left])/(arr[right]-arr[left])))
    midVal = arr[mid]
    
    
    if findVal > midVal:
        return insertSearch(arr,mid+1,right,findVal)
    elif findVal<midVal:
        return insertSearch(arr,left,mid-1,findVal)
    else:
        temp = mid - 1
        while(True):#左边
            if temp>len(arr)-1 or arr[temp]!=findVal:
                break
            resIndex.append(temp+1)
            temp-=1
            
        resIndex.append(mid+1)#中间
        
        temp=mid+1
        while(True):#右边
            if temp<0 or arr[temp]!=findVal:
                break
            resIndex.append(temp+1)
            temp+=1
        return resIndex
    
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
print("Index="+str(insertSearch(arr,0,len(arr)-1,1)))
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

Fibonacci lookup

Fibonacci search : After reading the above two search methods, you find that the search algorithm is an algorithm that separates the data and approaches the target value, and mathematically there is a classic split method-the golden section 0.618. And the golden section happens to have a mathematical relationship with the Fibonacci sequence. Using the Fibonacci sequence to divide the previous number and the next number, it just happens to get closer to the golden ratio. From this we have produced a new search algorithm: Fibonacci search.

import copy
#arr = [1,8,10,89,1000,1234]

import time

arr = [0 for i in range(9000)]
for i in range(9000):
    arr[i]=i

def fib():#非递归
    f = [0 for i in range(9000)]
    f[0]=1
    f[1]=1
    for i in range(2,9000,1):
        f[i]=f[i-1]+f[i-2]
    return f

def fibSearch(arr,key):
    low = 0
    high=len(arr)-1
    k = 0               #分割数字的下标
    mid = 0
    f = fib()
    #获取斐波那契分隔数的下标
    while(high>f[k]-1):
        k+=1
    temp = copy.deepcopy(arr)
    for i in range(high+1,f[k],1):
        temp.append(arr[high])
    
    while(low<=high):
        mid = low+f[k-1]-1
        if key<temp[mid]:#左边查找
            high=mid-1
            k-=1
        elif key>temp[mid]:#右边查找
            low=mid+1
            k-=2
        else:
            if mid<=high:
                return mid
            else:
                return high
    return -1
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))           
print("Index="+str(fibSearch(arr,11) ))     
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) 
Published 27 original articles · praised 2 · visits 680

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/105380816