import random
插入排序:如果原始数据基本有序 则插入排序的时间复杂度就会很小
希尔排序:
1:元素多的时候 元素少
2:元素多的时候 元素基本有序
实现:
#注意点:将增量的每一个元素往自己的组里面去插,而非一个一个组中进行排序
def shellSort(ls):
mLen = len(ls)
interval = mLen//2
while interval > 0:
#外层循环 表示进行多少次切分
for i in range(interval, mLen, 1):
#这里循环里面进行插入排序
value = ls[i]
index = i-interval
while index > -1 and value < ls[index]:
ls[index+interval] = ls[index]
index = index - interval
ls[index + interval] = value
interval = interval // 2
问题:
这个问题进行希尔排序已经退化到插入排序 希尔排序的最坏情况
问题:
这个问题属于进行希尔排序的最好情况
#冒泡排序
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
#插入排序
#解法1
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
#解法2
def insertionSort(ls):
if len(ls) <= 1:
return
for i in range(1, len(ls)):
for j in range(i):
if ls[i] >= ls[j]:
pass
else:
value = ls[i]
for k in range(i-j):
#往前移
ls[i-k] = ls[i-k-1]
#将这个值赋予过去
ls[j] = value
#归并排序
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)))
##时间复杂度度+稳定性