import random
#冒泡排序
def bubbleSort(ls):
if len(ls) <= 1:
return ls
for i in range(len(ls)-1):
for j in range(0, len(ls)-i-1):
if ls[j] > ls[j+1]:
ls[j], ls[j+1] = ls[j+1], ls[j]
return ls
#选择排序
def selectionSort(ls):
if len(ls) <= 1:
return ls
for i in range(len(ls)):
myMin = i
for j in range(i, len(ls)):
if ls[j] < ls[myMin]:
myMin = j
ls[i],ls[myMin] = ls[myMin], ls[i]
return ls
#插入排序
def insertionSort(ls):
if len(ls) <= 1:
return ls
for i in range(1,len(ls)):
for j in range(i):
if(ls[i] < ls[j]):
ls[i+1:j+1] = ls[i:j]
ls[j] = ls[i]
return ls
#归并排序
def MergeList(left, right):
mList = []
while left and right:
if left[0] > right[0]:
mList.append(right.pop(0))
else:
mList.append(left.pop(0))
while left:
mList.append(left.pop(0))
while right:
mList.append(right.pop(0))
return mList
def MergeSort(ls):
if len(ls) <= 1:
return ls
middle = len(ls)//2
left, right = ls[:middle], ls[middle:]
return MergeList(MergeSort(left), MergeSort(right))
#快速排序
def quickSort(ls):
if len(ls) <= 1:
return ls
left = []
right = []
for i in ls[1:]:
if ls[0] > i:
left.append(i)
else:
right.append(i)
return quickSort(left)+[ls[0]]+quickSort(right)
#计数排序
def countingSort(ls):
ls1 = [None] * len(ls)
for i in ls:
count = 0
count1 = 0
for j in range(len(ls)):
if i > ls[j]:
count += 1
elif i == ls[j]:
count1 += 1
for k in range(count, count+count1):
ls1[k] = i
return ls1
#生成位于[0,100)数量为n的随机列表
def randomList(n):
iList = []
for i in range(n):
iList.append(random.randrange(100))
return iList
if __name__ == "__main__":
print(bubbleSort(randomList(100)))
print(selectionSort(randomList(100)))
print(selectionSort(randomList(100)))
print(MergeSort(randomList(100)))
print(quickSort(randomList(100)))
print(countingSort(randomList(100)))



