《算法导论》第三版 P22,2.3-5练习题
递归实现
list1 = [1,2,3,4,5,6,7,8,9,10];
count = len(list1);
def rbs(list0, start, end, a):
mid = (int)((start + end) / 2);
if a == list0[mid]:
return mid
if start == mid and mid == end:
return -1
index1 = rbs(list0, start, mid - 1);
index2 = rbs(list0, mid + 1, end);
if index1 == -1:
return index2
else:
return index1
print("Index of 5 is:");
print(rbs(list1, 0, count - 1, 5));
非递归实现
list1 = [1,2,3,4,5,6,7,8,9,10];
count = len(list1);
stack = []
def bs(list0, start, end, a):
while(True):
mid = (int)((start + end) / 2)
if a == list0[mid]:
return mid
if start == mid and mid == end:
if len(stack) == 0:
return -1
else:
start = stack.pop(0)
end = stack.pop(0)
mid = -1
if mid != -1:
stack.append(mid + 1)
stack.append(end)
end = mid
print("Index of 5 is:");
print(bs(list1, 0, count - 1, 5));
注:单递归改成非递归,用循环就能解决;双递归改成非递归,除了用循环之外,还要借助栈或者队列。
作者:李印臣,2005年毕业于山东师范大学计算机系,曾三次患有精神分裂症。康复后,做了近四年的软件工程师,然后做了两年精神分裂症领域的公益,现重新回到软件行业,一切从头再开始!
愿这个博客见证我的成长与进步。