相关简单算法代码(顺序,二分,冒泡,插入,选择等)
顺序查找
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def linear_search(li,val): 2 for i,k in enumerate(li): 3 if k == val: 4 return i 5 6 else: # for循环完毕后一定会执行else 7 return None
二分法查找
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 二分算法代码 2 3 def binary_search(list,val): 4 left = 0 5 right = len(list)-1 6 while left<=right: # 候选区有值 7 mid = (left + right) // 2 8 if list[mid] ==val: 9 return mid 10 elif list[mid] > val: 11 right = mid - 1 12 else: 13 left = mid + 1 14 else: 15 return None 16 list = [1,2,3,4,4,6,7] 17 print(binary_search(list,8))
冒泡排序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 冒泡排序 2 def bubble_sort(li): 3 for i in range(len(li)-1): # i表示趟数 4 exchange = False # 没有移动数字 5 for j in range(len(li)-i-1): 6 if li[j] > li[j+1]: 7 li[j],li[j+1] = li[j+1],li[j] 8 exchange = True 9 print(li) 10 if not exchange: 11 break 12 13 14 15 li = [1,2,3,4,6,5,8] 16 f = bubble_sort(li)
插入排序
# 插入排序 def insert_sort(li): for i in range (1,len(li)): # i表示拿到的数字索引 j = i-1 # j 表示有序区最后一个的索引 tmp = li[i] while j>=0 and li[j]>tmp: li[j+1] = li[j] j -= 1 li[j+1] = tmp print(li) li = [1,5,6,8,5,2] print(li) insert_sort(li)
选择排序
# 选择排序 def select_sort(li): for i in range (len(li)-1): # i 表示趟数 for j in range(i+1,len(li)): if li[j]<li[i]: #li[i]表示最小 li[i],li[j] = li[j],li[i] print(li) li = [2,1,2,5,6] print(li) select_sort(li)
作者:华王
博客:https://www.cnblogs.com/huahuawang/