冒泡排序
a = [2,1,3,5,6,7,8,4]
for i in range(len(a)):
for j in range(len(a)-1):
if a[j]>a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
print(a)
选择排序
a = [2,1,3,5,6,7,8,4]
for i in range(len(a)-1):
index = i
for j in range(i+1,len(a)):
if a[index]>a[j]:
index = j
a[i],a[index]=a[index],a[i]
print(a)
快速排序
def quickSort(array,start,end):
a,b = start,end
if a>=b:
return
base = array[start]
while a<b:
while a<b and array[b]>=base:
b -= 1
array[a] = array[b]
while a<b and array[a]<base:
a += 1
array[b] = array[a]
array[a] = base
quickSort(array,start,a-1)
quickSort(array,b+1,end)
return array
a = [2,1,3,5,6,7,8,4]
b = quickSort(a,0,7)
归并排序
def sort_1(list1,list2):
j,h = 0,0
c = []
while j<len(list1) and h<len(list2):
if list1[j] >= list2[h]:
c.append(list2[h])
h += 1
elif list1[j] < list2[h]:
c.append(list1[j])
j += 1
if j==len(list1):
c.extend(list2[h:])
elif h==len(list2):
c.extend(list1[j:])
return c
def sort_2(array):
if len(array)<=1:
return array
mid = len(array)//2
left = sort_2(array[:mid])
right = sort_2(array[mid:])
return sort_1(left,right)
a = [2,1,3,5,6,7,8,4]
b = sort_2(a)