一、选择排序
def selectionSort(lst):
'''选择排序'''
i = 0
while i < len(lst) - 1:
minIndex = i
j = i + 1
while j < len(lst):
if lst[j] < lst[minIndex]:
minIndex = j
j += 1
if minIndex != i:
lst[i], lst[minIndex] = lst[minIndex], lst[i]
i += 1
return lst
二、冒泡排序
def bubbleSort(lst):
'''冒泡排序'''
n = len(lst)
while n > 1:
i = 1
swapped = False
while i < n:
if lst[i] < lst[i-1]:
lst[i], lst[i-1] = lst[i-1], lst[i]
swaped = True
i += 1
if not swapped:
return lst
n -= 1
return lst
三、插入排序
def insertionSort(lst):
i = 1
while i < len(lst):
itemToIndex = lst[i]
j = i - 1
while j >= 0:
if itemToIndex < lst[j]:
lst[j+1] = lst[j]
j -= 1
else:
break
lst[j+1] = itemToIndex
i += 1
return lst
网友评论