###插入排序(O(n**2))###
def insert_sort(alist):
if len(alist) == 1:
return alist
else:
for i in range(len(alist)-1,0,-1):
for j in range(i,0,-1):
if alist[j] < alist[j-1]:
alist[j],alist[j-1] = alist[j-1],alist[j]
else:
break
###冒泡排序(O(n**2))###
def bubble_sort(alist):
if len(alist) == 1:
return alist
else:
for i in range(len(alist)-1,0,-1):
for j in range(i):
if alist[j] > alist[j+1]:
alist[j],alist[j+1] = alist[j+1],alist[j]
return alist
###归并排序(O(nlogn))###
def merge(left,right):
res = []
i,j = 0,0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
res.append(left[i])
i += 1
else:
res.append(right[j])
j += 1
res += left[i:]
res += right[j:]
return res
def merge_sort(alist):
if len(alist) == 1:
return alist
else:
mid = round(len(alist)/2)
left = alist[:mid]
right = alist[mid:]
return merge(left,right)
基础算法(python)
最新推荐文章于 2024-08-24 14:07:53 发布