Python之 常用查詢演算法:最小項搜尋、順序搜尋、二分搜尋

ckxllf發表於2019-09-30

  最小項搜尋

  def min_search(items):

  """

  最小項搜尋

  :param items:

  :return:

  """

  min_index = 0

  for i in range(len(items)):

  if items[min_index] > items[i]:

  min_index = i

  return 'min index: {}'.format(min_index)

  順序搜尋

  def order_search(target, items):

  """

  順序搜尋,常用遍歷方法, O(n)

  :param target:

  :param items:

  :return:

  """

  position = 0

  while position < len(items):

  if target == items[position]:

  return 'where index: {}'.format(position)

  position += 1

  return '404 Not FOUND!:('

  二分(叉)搜尋

  def binary_search(target, items):

  """

  二分查詢(二叉搜尋),O(log2n)

  前置條件:列表已排好序

  :param target:

  :param items:

  :return: 無錫看婦科的醫院

  """

  left = 0

  right = len(items) - 1

  while left <= right:

  middle = (left + right) // 2

  if target == items[middle]:

  return 'where index: {}'.format(middle)

  elif target > items[middle]:

  left = middle + 1

  else:

  right = middle - 1

  return -1

  測試 main() 函式示例

  if __name__ == '__main__':

  items1 = [1, 3, 6, 23, 0]

  min_search_res = min_search(items1)

  print('最小值索引:', min_search_res)

  items2 = [1, 3, 6, 23, 66]

  order_search = order_search(23, items2)

  print('順序查詢:', order_search)

  items3 = [1, 3, 6, 23, 66]

  search_res = binary_search(66, items3)

  print('二分查詢:', search_res)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69945560/viewspace-2658847/,如需轉載,請註明出處,否則將追究法律責任。

相關文章