您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法 二分法查找【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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: