常见的排序算法:冒泡排序,选择排序,插入排序,希尔排序,快速排序,堆排序,归并排序。
冒泡排序原理 :两两元素进行比较,每一趟能够确定最大元素的位置,稳定算法
def bubble_sort(alist):
'''冒泡排序'''
# [5,4,3,2,1] [4,5,3,2,1] [4,3,5,2,1] [4,3,2,5,1] [4,3,2,1,5]
n = len(alist)
for i in range(n):
# count = 0
for j in range(0,n-1):
if alist[j]>alist[j+1]:
alist[j],alist[j+1] = alist[j+1],alist[j]
count+=1
# if count==0:
# break
return alist
选择排序原理: 每次从待排序列选择最小的元素,放在已排序列依次后面,不稳定算法
def select_sort(alist):
'''选择排序'''
# [5,4,3,2,1] [1,4,3,2,5] [1,2,3,4,5] [1,2,3,4,5]
n = len(alist)
for i in range(n):
min_index = i
for j in range(i+1,n):
if alist[min_index]>alist[j]:
min_index = j
alist[min_index],alist[i] = alist[i],alist[min_index]
return alist
插入排序原理: 将待排序列分为已排序和未排序,每次从未排序序列选择依次元素放在相应位置,稳定算法
def insert_sort(alist):
'''插入排序'''
# [5,4,3,2,1] [4,5,3,2,1] [3,4,5,2,1] [2,3,4,5,1] [1,2,3,4,5]
n = len(alist)
for i in range(1,n):
while i>0:
if alist[i-1]>alist[i]:
alist[i-1],alist[i] = alist[i],alist[i-1]
i = i-1
else:
break
return alist
希尔排序原理: 希尔排序是插入排序的变种,插入排序是间隔为0,而希尔排序的间隔自己确定,不稳定算法
def shell_sort(alist):
'''希尔排序'''
# [5,4,3,2,1] ([5,3,1] [4,2]) ([3,5,1] [2,4]) ([1,3,5] [2,4])[1,2,3,4,5]
n = len(alist)
gap = n
while gap>0:
for i in range(gap,n):
while i > 0:
if alist[i - gap] > alist[i]:
alist[i - gap], alist[i] = alist[i], alist[i - gap]
i = i - gap
gap = gap//2
return alist
快速排序原理: 快速排序是每次选择一个哨兵,比哨兵小的放在前面,比哨兵大的放在后面,这样每趟都能确定中间位置元素的,不稳定算法
def quick_sort(alist):
'''快速排序'''
# [5,4,3,2,1] []
n = len(alist)
if n<=1:
return alist
else:
pivot = alist[0]
low = [low for low in alist[1:] if low
=pivot]
return quick_sort(low)+[pivot]+quick_sort(high)
归并排序的原理: 归并排序借助额外空间,从而减小了时间复杂度,属于选择排序的变种,稳定算法
def merge_sort(alist):
'''归并排序'''
# [5,4,3,2,1] ([5] [4] [3] [2] [1]) ([4,5] [])
n = len(alist)
if n<=1:
return alist
if n>1:
midpoint = n//2
left = merge_sort(alist[:midpoint])
right = merge_sort(alist[midpoint:])
print('left:',left)
print('right:',right)
print('===================')
k = 0
i = 0
j = 0
# if len(left) and len(right):
while i < len(left) and j < len(right):
if left[i] < right[j]:
alist[k] = left[i]
i = i+1
else:
alist[k] = right[j]
j = j+1
k = k+1
while i
堆排序原理: 堆排序稍微复杂一点,他需要先构造堆,分为大顶堆和小顶堆,大顶堆对应升序,小顶堆对应降序,构造完之后才是排序,每次从堆顶取出元素放入到待排序列末尾。不稳定算法
def heap_create(alist,index,heap_size):
largest = index
left_index = 2*index+1
right_index = 2*index+2
if left_index