# Python—算法——-归并排序，二分查找

1146-陶同学

## 归并排序：

def merge_sort(alist):
n = len(alist)
if n <= 1:
return alist
mid = n // 2
# left，right 采用归并排序后形成的有序的新的列表
left_li = merge_sort(alist[:mid])
right_li = merge_sort(alist[mid:])
# 将两个有序的子序列合并为一个新的整体
# merge(left,right)
left_pointer, right_pointer = 0, 0
result = []
while left_pointer < len(left_li) and right_pointer < len(right_li):
if left_li[left_pointer] < right_li[right_pointer]:
result.append(left_li[left_pointer])
left_pointer += 1
else:
result.append(right_li[right_pointer])
right_pointer += 1
result += left_li[left_pointer:]
result += right_li[right_pointer:]
return result

## 二分查找：

def binary_search(alist, item):
first = 0
last = len(alist)-1
while first<=last:
midpoint = (first + last)/2
if alist[midpoint] == item:
return True
elif item < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return False
def binary_search(alist, item):
n = len(alist)
if n > 0:
mid = n // 2
if alist[mid] == item:
return True
elif item < alist[mid]:
return binary_search(alist[:mid])
else:
return binary_search(alist[mid:])
return False


Vieu3.3主题

Q Q 登 录