二分法查找
给定一个排好序(升序)的列表与待查找的关键字,成功则返回其索引,失败则返回-1。
def search(list1, key):
left = 0 # 设置列表左边界索引
right = len(list1) - 1 # 设置列表右边界索引
while left <= right: # 判断是否查找完成
mid = (left + right)// 2 # 中间索引
if key > list1[mid]: # 若条件成立,则key在右半部分
left = mid + 1
elif key < list1[mid]:
right = mid - 1
else:
return mid
else:
return -1
冒泡排序
思路:比较两个相邻下标所对应的元素,如果符合条件则交换位置
def bubble(list1):
for time in range(1, len(list1)): # time即循环轮数
for index in range(len(list1) - time):
if list1[index] > list1[index + 1]:
list1[index], list1[index + 1] = list1[index + 1], list1[index]
return list1
选择排序
思路:从前往后,固定一个下标,然后使用这个下标对应的元素和列表中其他的元素进行依次比对,如果符合条件则交换位置
def selection(list1):
for key in range(len(list1) - 1):
for index in range(key + 1, len(list1)):
if list1[key] > list1[index]:
list1[key], list1[index] = list1[index], list1[key]
return list1