查找
二分查找
#非递归实现二分查找
def bannary_search(alist,a):
n = len(alist)
start = 0
end = n-1
while start <= end:
mid = (start + end) // 2
if alist[mid] == a:
return True
elif alist[mid] > a:
end = mid - 1
elif alist[mid] < a:
start = mid + 1
return False
def binarry_search(alist,b):
n = len(alist)
mid = n//2
if n == 0:
return False
if alist[mid] == b:
return True
elif alist[mid] > b:
return binarry_search(alist[0:mid], b)
else:
return binarry_search(alist[mid+1:], b)
if __name__=='__main__':
alist = [2, 3, 4, 5, 6, 7]
# print(bannary_search(alist, 77))
print(binarry_search(alist, 22))
顺序查找
def linear_search(li,val):
for ind, v in range(range(li)):
if v == val:
return ind
else:
return None
def sequence_search(alist,a):
n = len(alist)
for i in range(n):
if alist[i] == a:
return i
return -1
if __name__ == '__main__':
alist = [43, 56, 23, 54, 36, 23, 78]
index = sequence_search(alist, 23)
if index != -1:
print("查找到的数为第", index, "个")
else:
print("未找到")
列表排序
常见的排序算法
冒泡排序
#冒泡排序,对列表进行升序排序
import random
def bubble_sort(list):
#相邻两个元素进行比较
n=len(list)
for k in range(n-1):
for i in range(n-1-k):
if list[i]>list[i+1]:
list[i],list[i+1]=list[i+1],list[i]
# list=[7,5,3,6,44,22,33,2]
bubble_sort(list)
print(list)
选择排序
def select_sort(slist):
n=len(alist)
for i in range(n-1):
min=i
for j in range(i+1,n-1):
if alist[min]>alist[j]:
min=j
alist[i],alist[min]=alist[min],alist[i]
alist=[5,33,5,67,9,71,34,55]
select_sort(alist)
print(alist)
插入排序
#插入排序
def insert_sort(alist):
n=len(alist)
for i in range(1,n):
j=i
for j in range(n):
while j>0:
if alist[j]<alist[j-1]:
alist[j],alist[j-1]=alist[j-1],alist[j]
else:
break
j=j-1
if __name__=='__main__':
alist=[2,55,43,56,87,99,0]
insert_sort(alist)
print(alist)