1.快速排序
过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小
一般选取第一个数作为关键数据k,我们要把比k小的所有数据移到它的左面,从后往前找第一个比它小的数据,交换位置
比k大的数据移到它的右面,从前往后找第一个比它大的数据,交换位置,完成一个循环。
def quick1_sort(list):
if len(list) < 2:
return list
else:
key = list[0]
small = [i for i in list[1:] if i < key]
big = [j for j in list[1:] if j > key]
list = quick1_sort(small) + [key] + quick1_sort(big)
return list a1 = quick1_sort([2,1,4,3,6,5,7,8,10])
print(a1)
def quick_sort(list, left, right):
if left >= right:
return list
key = list[left]
low = left
high = right
while left < right:
while left < right and list[right] >= key:
right -= 1
list[left] = list[right]
while left < right and list[left] <= key:
left += 1
list[right] = list[left]
list[right] = key
quick_sort(list, low, left - 1)
quick_sort(list, left + 1, high)
return list s=[2,1,4,5,3,6,7,9,8]
a = quick_sort(s,0,len(s)-1)
print(a)
2.希尔排序
希尔排序是插入排序的增强版
1.首先知道整个列表的长度N,设置步数为step=N/2(取整数),
从第一个元素开始,每相隔为step的两个元素组成一组,按照直接插入的方法对每个小组进行排序,完成第一次排序
2.第二次排序将步数缩减一半,即step1=step/2,在按照步骤一的方法进行排序
3.重复步骤2,直到变成有序
def shell_sort(list):
gap = len(list)//2
while gap > 0:
for i in range(0, gap):
j = i+gap
while j < len(list):
k = j - gap
key = list[j]
while k >= 0:
if list[k] > key:
list[k+gap] = list[k]
list[k] = key
k -= gap
j += gap
gap = gap//2
return list a = shell_sort([2,1,4,3,9,7,8,6])
print(a)
def shell1_sort(list):
gap = len(list)//2
while gap > 0:
for i in range(gap, len(list)):
key = list[i]
j = i
while j >= gap:
if list[j-gap] > key:
list[j] = list[j-gap]
list[j-gap] = key
j = j - gap
gap = gap//2
return list a1 = shell1_sort([2,1,4,3,9,7,8,6])
print(a1)
3.归并排序
使用分割的方法将这个序列分割成一个个已经排好序的子序列,再利用归并的方法将其合成一个排序好的序列
#拆解的函数
def merge_sort(list):
if len(list) < 2:
return list
mid_length = len(list)//2
left = merge_sort(list[:mid_length])
right = merge_sort(list[mid_length:])
return merge(left,right)#合并 #return merge1(left, right) #合并函数
def merge(left, right):
result = []
while left and right:
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
while left:
result.append(left.pop(0))
while right:
result.append(right.pop(0))
return result def merge1(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result a = merge_sort([4,7,1,2,8,9,3,6])
print(a)