'''
1、冒泡排序------直接交换数值的位置
'''
def bubble_sort(alist):
n = len(alist)
for j in range(n-2):
for i in range(0,n-1-j):
if alist[i] > alist[i+1]:
alist[i],alist[i+1] = alist[i+1],alist[i]
'''2、选择排序-----通过下标的更换实现值的交换'''
def select_sort(alist):
n = len(alist)
for j in range(n-1):
min_index = j
for i in range(j+1,n):
if alist[min_index] > alist[i]:
min_index = i
alist[j],alist[min_index] = alist[min_index],alist[j]
'''3、插入算法'''
def insert_sort(alist):
n = len(alist)
for j in range(1,n):
i = j
while i > 0:
if alist[i] < alist[i-1]:
alist[i],alist[i-1] = alist[i-1],alist[i]
i -=1
else:
break
'''4、希尔排序------和插入排序原理相似'''
class shell_order(alist):
n = len(alist)
gap = n // 2
while gap >=1:
for j in range(gap,n):
i = j
while i >0:
if alist[i] < alist[i-gap]:
alist[i] ,alist[i-gap] = alist[i-gap] ,alist[i]
i -= gap
gap // 2
'''5、快速排序'''
class quick_sort(alist,first,last):
if first >= last:
return
mid_value = alist[first]
low = first
high = last
while low < high:
while low < high and mid_value <= alist[high]:
high -=1
alist[low] = alist[high]
while low < high and alist[low] < mid_value:
low +=1
alist[high] = alist[low]
mid_value = alist[low] #返回时low==high
#对low左边的列表进行快排
quick_sort(alist,first,low-1)
# 对low右边的列表进行快排
quick_sort(alist,low+1,last)
'''6、归并算法'''
class merge_sort(alist):
n = len(alist)
if n <= 1:
return alist
mid = n//2
left_li = merge_sort(alist[:mid])
ringht_li = merge_sort(alist[mid:])
left_pointer,ringht_pointer = 0,0
result = []
while left_pointer < len(left_li) and ringht_pointer < len(ringht_li):
if left_li[left_pointer] < ringht_li[ringht_pointer]:
result.append(left_li[left_pointer])
left_pointer +=1
else:
result.append(ringht_li[ringht_pointer])
ringht_pointer +=1
result += left_li[left_pointer]
result +=ringht_li[ringht_pointer]
return result
6种常见的排序算法
猜你喜欢
转载自blog.csdn.net/xiaoyaosheng19/article/details/82870981
今日推荐
周排行