冒泡排序
def bubbleSort(lst):
for n in range(len(lst)-1,0,-1):
for i in range(n):
if lst[i] > lst[i+1]:
temp = lst[i]
lst[i] = lst[i+1]
lst[i+1] = temp
选择排序
def selectionSort(lst):
for n in range(len(lst) - 1, 0, -1):
max = n
for i in range(n+1):
if lst[i]>lst[max]:
max = i
temp = lst[n]
lst[n] = lst[max]
lst[max] = temp
插入排序
def insertSort(lst):
for n in range(1,len(lst)):
value = lst[n]
i = n-1
while i > -1 and lst[i]>value:
lst[i+1] = lst[i]
i -= 1
lst[i+1] = value
归并排序
def mergeSort(lst):
if len(lst)>1:
mid = len(lst)//2
lefthalf = lst[:mid]
righthalf = lst[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i,j,k = 0,0,0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
lst[k] = lefthalf[i]
i += 1
else:
lst[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
lst[k] = lefthalf[i]
i += 1
k += 1
while j < len(righthalf):
lst[k] = righthalf[j]
j += 1
k += 1
快速排序
def quickSort(lst,l,r):
if l >= r:
return
low,high = l,r
temp = lst[low]
while low < high:
while low < high and lst[high] >= temp:
high -= 1
lst[low] = lst[high]
while low < high and lst[low] <= temp:
low += 1
lst[high] = lst[low]
lst[low] = temp
quickSort(lst,l,low-1)
quickSort(lst,low+1,r)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)