算法
二分法:
n = 100 li = list(range(n)) def bin_search(li,val): low = 0 high = len(li) - 1 while low <= high: mid = (low + high) // 2 if li[mid] == val: return mid elif li[mid] < val: low = mid + 1 else: high = mid - 1 return None obj = bin_search(li,33) print(obj)
# 算法网址 https://leetcode.com/problems/two-sum/description/ #方式一: def two_sum(li,target): l = len(li) for i in range(l): for j in range(i+1,l): if li[i] + li[j] == target: return (i,j) return None obj = two_sum([2,7,11,15],18) print(obj) #方式二: def bin_search(data_set, value): low = 0 high = len(data_set) - 1 while low <= high: mid = (low + high) // 2 if data_set[mid] == value: return mid elif data_set[mid] > value: high = mid - 1 else: low = mid + 1 def two_sum2(li, target): li.sort() for i in range(len(li)): b = target - li[i] j = bin_search(li, b) if j != None and i != j: return i, j obj = two_sum2([2, 7, 11, 15], 18) print(obj) #方式三: def two_sum3(li,target): li.sort() i = 0 j = len(li) - 1 while i < j: sum = li[i] + li[j] if sum > target: j-=1 elif sum < target: i+=1 else: return (i,j) return None obj = two_sum3([2,7,11,15],18) print(obj)
排序:
#冒泡排序 - 列表每相邻的数,如果前面的比后面的大,那么交换这两个数 -算法复杂度 n^2 def bubble_sort(li): for i in range(len(li) - 1): for j in range(len(li) - i -1): # i 趟 if li[j] > li[j+1]: li[j+1],li[j] = li[j],li[j+1] # j 指针 return li li = [9,1,5,3,7] print(bubble_sort(li))
#选择排序 - 一趟遍历记录 最小的数,放到第一个位置。再一趟遍历记录剩余列表中最小的数,继续放置 - 时间复杂度 O(n^2) def select_sort(li): for i in range(len(li) - 1): min_loc = i # 找i+1位置到最后位置内 最小的数 for j in range(i+1,len(li)): if li[j] < li[min_loc]: min_loc = j # 和无序区第一个数 做交换 li[i],li[min_loc] = li[min_loc],li[i] return li li = [9,3,7,1] print(select_sort(li))
#插入排序 - 列表被分为有序区和无序区 最初有序区只有一个元素 - 每次从无序区选择一个元素 插入到有序区的位置 直到无序区变空 #方式一: def insert_sort(li): for i in range(1,len(li)): # i 代表每次摸到牌的下标 tmp = li[i] j = i-1 # j代表手里最后一张牌的下标 while True: if j<0 or tmp>=li[j]: break li[j+1] = li[j] j -= 1 li[j+1] = tmp return li obj = insert_sort([1,8,6,2,5,3]) print(obj) #方式二: def insert_sort(li): for i in range(1,len(li)): # i 代表每次摸到牌的下标 tmp = li[i] j = i-1 # j代表手里最后一张牌的下标 while j>=0 and tmp<li[j]: li[j+1] = li[j] j -= 1 li[j+1] = tmp return li obj = insert_sort([1,8,6,2,5,3]) print(obj)
def partition(data,left,right): tmp = data[left] while left < right: # right 左移动 while left < right and data[right] >= tmp: #如果low和high没有相遇且后面的数一直大于第一个数 就循环 right -=1 data[left] = data[right] # left 右移动 while left < right and data[left] <= tmp: #如果low和high没有相遇且后面的数一直大于第一个数 就循环 left +=1 data[right] = data[left] data[left] = tmp return left def quick_sork(data,left,right): if left <right: mid = partition(data,left,right) quick_sork(data,left,mid-1) quick_sork(data,mid+1,right) return data alist = [33,22,11,55,33,666,55,44,33,22,980] obj = quick_sork(alist,0,len(alist)-1) print(obj)