Python 实现查找的几种类型 (线性查找,线性有序查找,线性查找最小值,二分查找)
2015-01-15 15:11
555 查看
#!/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
相关文章推荐
- 线性查找与二分查找(java实现)
- 算法学习---基本数据类型的数组二分查找实现
- Python实现二维有序数组查找的方法
- 二分查找的两种实现方式(递归和非递归)--python实现
- js实现类型判断,二分查找与日期格式化
- 用Python实现二分查找
- python实现的二分查找
- Python实现二分查找与bisect模块详解
- python实现二分查找
- 二分查找的几种方法对比,C++实现
- 实现有序列表(基于数组,二分查找)
- python中实现二分查找,插入排序,归并排序,快速排序
- 算法学习---对象类型的数组二分查找实现
- 写一个函数,实现一个整形有序数组的二分查找
- 在一个旋转过的有序数组上实现二分查找 收藏
- 算法学习---基本数据类型的数组二分查找实现
- Python实现二分查找
- 二分查找算法之python实现
- 二分法实现一个整形有序数组的二分查找
- 【二分查找】用C语言实现一个有序数组的二分查找