第四类搜索算法

时间:2016-10-04 06:36:26

标签: pseudocode

我应该为四元搜索算法编写代码。我得到的唯一描述是它是对二进制搜索算法的修改,但不是将数组拆分为两个,而是将数组拆分为四个。

我对这样的搜索究竟是如何工作有点困惑。我搜索了一些伪代码,甚至只是一个YouTube视频,解释/可视化搜索的工作原理,但我还没有找到任何东西。

是否有人对此搜索算法的工作方式有伪代码或快速而肮脏的解释?

谢谢!

3 个答案:

答案 0 :(得分:2)

array (size=5)
  'car1' => boolean true
  'car2' => boolean false
  'car3' => boolean false
  'car4' => boolean true
  'car5' => boolean true

答案 1 :(得分:2)

def Ping(url):
     r =  requests.get(url) #http://192.168.1.10
     if r.status_code == 200:
            return True
     return False

答案 2 :(得分:0)

此算法是Divide and Conquer算法 ie 的示例,主要问题分为smallerindependentsimilar子问题。这些类型的问题通常通过递归来解决。

如果$ \ Theta(\ log_2 n)$,则四元搜索的时间复杂度与二元搜索的复杂度相同(存在较小的差异,渐近无关紧要)。

这是一个Python实现:

''' quaternary search STUDY
0 1 2 3 4 5 ... n-4 n-3 n-2 n-1
L      B1     B2    B3      R

- size of array to be split in 4 in each recursion ==> S_4 = R - L + 1
- size of each split ==> N_4 = S_4 >> 2
- last split will eventually be larger than N_4 due to the remainder of the division by 4

- length of FIRST subarray = N_4
- length of SECOND subarray = N_4
- length of THIRD subarray = N_4
- length of FOURTH subarray = N_4 + S_4 mod 4

- position of breakpoint 1 => B1 = L + N_4
- position of breakpoint 2 => B2 = L + 2*N_4
- position of breakpoint 3 => B2 = L + 3*N_4
'''

def qsearch(A, L, R, key): # i.e. qsearch(A,0,len(A)-1,key)
    '''
    Quaternary search (divide & conquer)
    INPUTS:
     A = sorted array
     L = index of leftmost element
     R = index of rightmost element
     key = value to be found
    OUTPUT:
     zero-indexed position of <key> or <-1> if <key> is not in tha input array
    '''
    if L <= R:
        N_4 = (R-L+1) >> 2
        #print(N_4, L, R)
        if A[L+N_4] == key:
            return L+N_4
        elif key < A[L+N_4]:
            return qsearch(A, L, L+N_4-1, key)
        elif A[L+2*N_4] == key:
            return L+2*N_4
        elif key < A[L+2*N_4]:
            return qsearch(A, L+N_4+1, L+2*N_4-1, key)
        elif A[L+3*N_4] == key:
            return L+3*N_4
        elif key < A[L+3*N_4]:
            return qsearch(A, L+2*N_4+1, L+3*N_4-1, key)
        else:
            return qsearch(A, L+3*N_4+1, R, key)
    else:
        return -1