Python學習筆記19(算法)
阿新 • • 發佈:2017-08-30
while bdc bubble == append 算法 ef7 -a +=
1.二分查找
只能用二分查找查找有序列表
def bin_search(data,val): #data為被查找的列表,val是要查找的值 low = 0 high = len(data) - 1 while low <= high: mid = (low+high)//2 if data[mid] == val: return mid #找到了,返回val所在的索引 elif data[mid] < val: low = mid + 1 else二分查找: high = mid - 1 return #未找到,返回None
2.冒泡排序
def bubble_sort(data): #data傳需要排序的列表 for i in range(len(data)-1): FLAG = 0 for j in range(len(data)-i-1): if data[j] > data[j+1]: data[j],data[j冒泡排序+1] = data[j+1],data[j] FLAG = 1 if FLAG == 0: break
3.選擇排序
def select_sort(data): for i in range(len(data)-1): min = i for j in range(i+1,len(data)): if data[j] < data[min]: min = j data[i],data[min]選擇排序= data[min],data[i]
4.插入排序
def insert_sort(data): for i in range(1,len(data)): tmp = data[i] j = i - 1 while j >= 0 and data[j] > tmp: data[j+1] = data[j] j = j - 1 data[j + 1] = tmp插入排序
5.快速排序
def quick_sort(data,left,right): if left < right: mid = partition(data,left,right) quick_sort(data,left,mid - 1) quick_sort(data,mid + 1,right) def partition(data,left,right): tmp = data[left] while left < right: while left < right and data[right] >= tmp: right -= 1 data[left] = data[right] while left < right and data[left] <= tmp: left += 1 data[right] = data[left] data[left] = tmp return left快速排序
6.堆排序
def sift(data,low,high): i = low j = 2 * i +1 tmp = data[i] while j <= high: if j + 1 <= high and data[j] < data[j+1]: j += 1 if data[j] > tmp: data[i] = data[j] i = j j = 2 * i + 1 else: break data[i] = tmp def heap_sort(data): n = len(data) for i in range(n // 2 - 1 ,-1 ,-1): sift(data,i,n-1) for i in range(n-1,-1,-1): data[0],data[i] = data[i],data[0] sift(data,0,i-1)堆排序
7.歸並排序
def merge(data,low,mid,high): i = low j = mid+1 tmp = [] while i <= mid and j <= high: if data[i] < data[j]: tmp.append(data[i]) i += 1 else: tmp.append(data[j]) j += 1 while i <= mid: tmp.append(data[i]) i += 1 while j <= high: tmp.append(data[j]) j += 1 data[low:high+1] = tmp def mergesort(data,low,high): if low < high: mid = (low+high)//2 mergesort(data,low,mid) mergesort(data,mid+1,high) merge(data,low,mid,high)歸並排序
Python學習筆記19(算法)