谢尔排序
def shellSort(alist):
sublistcount = len(alist) // 2 # 间隔设定
while sublistcount > 0:
for startposition in range(sublistcount): # 子列表排序
gapInsertionSort(alist,startposition,sublistcount)
print("After increments of size",sublistcount,
'The list is:',alist)
sublistcount = sublistcount // 2 # 间隔缩小
def gapInsertionSort(alist, start, gap):
for i in range(start+gap, len(alist), gap):
currentvalue = alist[i]
position = i
while position>=gap and alist[position-gap]>currentvalue:
alist[position] = alist[position-gap]
position = position-gap
alist[position] = currentvalue
归并排序
def mergeSort(alist):
if len(alist) > 1: # 基本结束条件
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf) # 递归调用
mergeSort(righthalf)
# 对排好序的左右部分进行合并
i = j = k = 0
# 拉链式交错把左右半部从小到大归并到结果列表中
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i = i+1
else:
alist[k] = righthalf[j]
j = j+1
k = k+1
# 归并左半部剩余项
while i<len(lefthalf):
alist[k] = lefthalf[i]
i = i+1
k = k+1
# 归并右半部剩余项
while j<len(righthalf):
alist[k] = righthalf[j]
j = j+1
k = k+1
def merge_sort(lst):
# 递归结束条件
if len(lst) <= 1:
return lst
# 分解问题,并递归调用
middle = len(lst) // 2
left = merge_sort(lst[:middle]) # 左半部排好序
right = merge_sort(lst[middle:]) # 右半部排好序
# 合并左右半部,完成排序
merged = []
while left and right:
if left[0] <= right[0]:
merged.append(left.pop(0))
else:
merged.append(right.pop(0))
merged.extend(right if right else left)
return merged
快速排序
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first] # 选定中值
leftmark = first+1 # 左右标初值
rightmark = last
done = False
while not done:
# 向右移动左标
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark = leftmark+1
# 向左移动右标
while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark-1
# 两标相错就结束移动
if rightmark < leftmark:
done = True
else:
# 左右标的值交换
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
# 中值就位
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
# 中值点,也是分裂点
return rightmark