数据结构与算法 二分法查找【Python与C】的实现
2017-09-04 22:34
405 查看
代码如下:
Python:
def ErFen(List ,Number ,Len):
left = 0
high = Len - 1
while left <= high:
mid = (left + high)//2
if Number > List[mid]:
left = mid + 1
elif Number < List[mid]:
high = mid - 1
elif Number == List[mid]:
return mid
return -1
a = [1,2,3,4,5,6,7,8,9,10]
number = int(input('请输入想要查找的数字:'))
Len = len(a)
print(ErFen(a,number,Len))
C:
#include <stdio.h>
/*binsearch : find x in v[0] <= v[1] <= ... <= v[n-1] */
int binsearch(int x, int v[], int n){
int low, high, mid;
low = 0;
high = n - 1;
while ( low <= high ) {
mid = (low + high) / 2;
if(x < v[mid]){
high = mid - 1;
}
else if(x > v[mid]){
low = mid + 1;
}
else{ /*found match*/
return mid;
}
}
return -1;
}
int main(){
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int location;
int number = 9;
location = binsearch(number, array, 11);
printf("%d\n", location);
return 0;
}
Python:
def ErFen(List ,Number ,Len):
left = 0
high = Len - 1
while left <= high:
mid = (left + high)//2
if Number > List[mid]:
left = mid + 1
elif Number < List[mid]:
high = mid - 1
elif Number == List[mid]:
return mid
return -1
a = [1,2,3,4,5,6,7,8,9,10]
number = int(input('请输入想要查找的数字:'))
Len = len(a)
print(ErFen(a,number,Len))
C:
#include <stdio.h>
/*binsearch : find x in v[0] <= v[1] <= ... <= v[n-1] */
int binsearch(int x, int v[], int n){
int low, high, mid;
low = 0;
high = n - 1;
while ( low <= high ) {
mid = (low + high) / 2;
if(x < v[mid]){
high = mid - 1;
}
else if(x > v[mid]){
low = mid + 1;
}
else{ /*found match*/
return mid;
}
}
return -1;
}
int main(){
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int location;
int number = 9;
location = binsearch(number, array, 11);
printf("%d\n", location);
return 0;
}
相关文章推荐
- python 实现二分法查找
- Python cookbook(数据结构与算法)实现查找两个字典相同点的方法
- 二分法查找的Python实现
- 递归实现二分法查找----python
- python实现二分法查找
- 【笔记】Python 实现目录及子目录文件的查找
- 二分法查找 --JS 实现
- 算法代码实现之二分法查找,Golang(Go语言)实现
- Python实现的数据结构与算法之链表详解
- python 查找文件夹下所有文件 实现代码
- Python实现单词查询&文件查找
- python实现的二分查找
- Python实现的根据文件名查找数据文件功能示例
- 用c语言实现二分法查找表格【数据结构】
- Python 二分法查找
- 排序和搜索(一)——python实现顺序查找
- Python实现二分查找
- Python脚本实现查找指定目录下包含指定关键字的文件
- python查找算法的实现-二分法
- 快速排序、二分法查找的PHP实现代码