Python 实现查找的几种类型 (线性查找,线性有序查找,线性查找最小值,二分查找)

#!/usr/bin/python 
# -*- coding: utf-8 -*-

'''
Created on 2015-1-15
@author: beyondzhou
@name: mysearch.py
'''

# Implementation of the linear search on an unsorted sequence
def linearSearch(theValues, target):
    n = len(theValues)
    for i in range(n):
        # If the target is in the ith element, return True
        if theValues[i] == target:
            return True
    return False   # If not found, return False

# Implemenation of the linear search on a sorted sequence
def sortedLinearSearch(theValues, item):
    n = len(theValues)
    for i in range(n):
        # If the target is found in the ith element, return True
        if theValues[i] == item:
            return True
        # If target is larger than the ith element, it's not in the sequence
        elif theValues[i] > item:
            return False

    return False

# Searching for the smallest value in an unsorted sequence
def findSmallest(theValues):
    n = len(theValues)
    # Assume the first item is the smallest value
    smallest = theValues[0]
    # Determine if any other item in the sequence is smaller
    for i in range(1,n):
        if theValues[i] < smallest:
            smallest = theValues[i]

    return smallest

# binary search
def binarySearch(theValues, target):
    # Start with the entire sequence of elements
    low = 0
    high = len(theValues) - 1

    # Repeadedly subdivide the sequence in half until the target is found
    while low <= high:
        # Find the midpoint of the sequence
        mid = (high + low) // 2
        # Does the midpoint contain the target?
        if theValues[mid] == target:
            return True
        # Or does the target precede the midpoint?
        elif target < theValues[mid]:
            high = mid - 1
        # Or does it follow the midpoint?
        else:
            low = mid + 1

    # If the sequence cannot be subdivided further, we're done
    return False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值