二进制搜索实现

时间:2015-06-03 23:14:48

标签: python algorithm search

我一直在实施5种不同的二进制方式(任务http://codekata.com/kata/kata02-karate-chop/)。你可以提出更多方法的想法吗?
这就是我所得到的:
1)

def left_chop(key, arr):
    l = 0
    r = len(arr)
    while l<r:
        m = (l+r)/2
        if key<=arr[m]:
            r = m 
        else:
            l = m+1
    return l if key == arr[l] else -1


2)

def left_chop(key, array, left = 0, right = None):
    if right == None:
        right = len(array)
    if left==right:
        return left if key == array[left] else -1
    m = (left+right)/2
    if key<=array[m]:
        return left_chop(key, array, left, m)
    else:
        return left_chop(key, array, m+1, right)


3)我知道,这与第一次非常相似

class find(object):
    def __init__(self, key, array):
        self.array = array
        self.key = key
        self.l = 0
        self.r = len(array)

    def left_chop(self):
        while self.l<self.r:
            self.step()
        return self.l if self.key == self.array[self.l] else -1

    def step(self):
        m = (self.l+self.r)/2
        if self.key<=self.array[m]:
            self.r = m
        else:
            self.l = m+1

我试图在功能编程风格中提出一些东西,但没有成功。

6 个答案:

答案 0 :(得分:1)

4)这个使用递归。如果中途正确,则返回索引。否则,它将数组分成两半并继续以这种方式搜索。

def getIndexOf(search, array):
    arrlen = len(array)
    halfindex = arrlen / 2 - ((arrlen % 2) / 2)
    value = array[halfindex]
    if len(array) < 2 and array[0] != search:
        return -1;
    if value == search:
        return halfindex
    elif search < value:
        return getIndexOf(search, array[0:halfindex])
    else:
        return getIndexOf(search, array[halfindex:arrlen] + halfindex)

答案 1 :(得分:1)

您可以使用生成器:

def chopper(array, val):
    edges = (0, len(array))
    while True:
        m = sum(edges)/2
        edges = (edges[0], m) if array[m] >= val else (m+1, edges[1])
        yield edges

def chopSearch(array, val):
    for l, r in chopper(array, val):
        if array[l] == val:
            return l
        if l==r:
            return -1

答案 2 :(得分:1)

1.直接实现二进制搜索算法。

def binary_search(seq, t):
min = 0
max = len(seq) - 1
  while True:
     if max < min:
       return -1
       m = (min + max) // 2
     if seq[m] < t:
       min = m + 1
     elseif seq[m] > t:
       max = m - 1
   else:
      return m
  1. 二元搜索的替代方法。

    def binarySearch(alist, item):
        first = 0
        last = len(alist)-1
        found = False
    while first<=last and not found:
         midpoint = (first + last)//2
    if alist[midpoint] == item:
       found = True
     else
    if item < alist[midpoint]:
    last = midpoint-1
     else:
    first = midpoint+1
        return found
    testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
    print(binarySearch(testlist, 3))
    print(binarySearch(testlist, 13))
    
  2. 3.在python编程中处理二进制搜索的第三种不同方式

       def binarySearch(alist, item):
            if len(alist) == 0:
                return False
            else:
                midpoint = len(alist)//2
                if alist[midpoint]==item:
                  return True
                else:
                  if item<alist[midpoint]:
                    return binarySearch(alist[:midpoint],item)
                  else:
                    return binarySearch(alist[midpoint+1:],item)
            testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
           print(binarySearch(testlist, 3))
           print(binarySearch(testlist, 13))
    

答案 3 :(得分:-1)

随机分组搜索。

  1. 当前节点= root。
  2. 重复但未找到。
    • 如果当前节点=所需的值,则找到。
    • 如果所需的整数小于根,则从0到索引(根)随机选择一个索引。设置当前节点=选择索引。
    • 否则,从根到n-1随机选择一个索引。设置当前节点=选择索引。

答案 4 :(得分:-1)

函数式编程意味着多个函数,每个函数都有自己的单一用途,它们为给定的输入返回相同的输出:

def chopSearch(array, value):
    while len(array) != 1:
        if value == getMiddle(array):
            return value
        else:
            array = getNewArray(array, lessThan(array, value))
    return if array[0] == value value else -1

def getMiddle(array):
    return if (len(array) % 2 == 0) array[len(array)/2] else array[(len(array)+1)/2]

def lessThan(array, value):
    return if getMiddle(array) > value true else false

def getNewArray(array, isLess):
    return if isLess array[0:getMiddle(array)] else array[getMiddle(array)+1:len(array)-1]

作为一个caviat,我不知道python所以我花了一分钟尝试写这个。随意修复你看到的任何pyton错误。

答案 5 :(得分:-1)

由PSF提供

In [1]: import bisect

In [2]: bisect??
def bisect_left(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e < x, and all e in
    a[i:] have e >= x.  So if x already appears in the list, a.insert(x) will
    insert just before the leftmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    return lo