声明:
本文给出 二分法搜索、合并两个已排序表 的算法的Python实现方法和运行结果;
代码有问题或疑惑下方评论,有错勿喷;更多大学简单算法的实现进我博客;
1. 二分法搜索 binary_search
程序代码
import math
def binary_search(A,num):
n = len(A)
low = 0
high = n-1
num_location = -1
count_compare = 0
while high - low > 1 and num_location == -1:
mid = math.floor( (low + high)/2 )
if A[mid] == num:
num_location = mid
elif A[mid] <= num:
low = mid
else:
high = mid
count_compare = count_compare + 1
if high - low == 1:
if A[low] == num:
num_location = low
elif A[high] == num:
num_location = high
count_compare = count_compare + 1
print('\n 输入的数组为:',A)
print(' 要搜索的数为:',num)
if num_location == -1:
print('\n 没有搜索到该值')
print(' 比较次数为:', count_compare)
else:
print('\n 在该数组的位置:', num_location+1)
print(' 比较次数为:', count_compare)
A = [-39, -22, -1, 5, 12, 21, 33, 56, 56, 76, 92, 92, 110, 999]
num = 110
binary_search(A,num)
运行结果
输入的数组为: [-39, -22, -1, 5, 12, 21, 33, 56, 56, 76, 92, 92, 110, 999]
要搜索的数为: 110
在该数组的位置: 13
比较次数为: 4
输入的数组为: [-39, -22, -1, 5, 12, 21, 33, 56, 56, 76, 92, 92, 110, 999]
要搜索的数为: 0
没有搜索到该值
比较次数为: 5
输入的数组为: [-39, -22, -1, 5, 12, 21, 33, 56, 56, 76, 92, 92, 110, 999]
要搜索的数为: -1000
没有搜索到该值
比较次数为: 4
2. 合并两个已排序的表 merge
程序代码
def merge(A1,A2):
a1 = 0
a2 = 0
n1 = len(A1)-1
n2 = len(A2)-1
B = [ 0 for i in range(n1+n2+1)]
b = 0
while a1<=n1 and a2<=n2:
if A1[a1] <= A2[a2]:
B[b] = A1[a1]
b = b+1
a1 = a1+1
else:
B[b] = A2[a2]
b = b+1
a2 = a2+1
print(B)
return B
A1 = [-34,-22,-11,2,9,20,30,78,243]
A2 = [-88,-20,-2,29,30,66,129]
print('\n 合并结果为:', merge(A1,A2) )
运行结果
[-88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 0, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 0, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 20, 0, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 20, 29, 0, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 20, 29, 30, 0, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 20, 29, 30, 30, 0, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 20, 29, 30, 30, 66, 0, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 20, 29, 30, 30, 66, 78, 0]
[-88, -34, -22, -20, -11, -2, 2, 9, 20, 29, 30, 30, 66, 78, 129]
合并结果为: [-88, -34, -22, -20, -11, -2, 2, 9, 20, 29, 30, 30, 66, 78, 129]