排序算法基本原理以及复杂度等知识点可跳转至该博客了解https://www.cnblogs.com/onepixel/p/7674659.html ,本博客主要对排序算法性能进行对比以及记录对比过程发现的问题
1. 插入排序和选择排序的对比
1.1 插入排序:从列表第一个元素 List[0] 开始每次取出列表一个元素,与该元素的前面元素进行比较,如果前面元素比该元素大,则把前面元素后移,直到前面元素不比该元素大,则插入。
插入排序示例
lst = [1,4,2,7,5]
----------------------第1次---------------------
取出lst[0] = 1; temp = lst[0]
前面没有元素,结束比较。
lst = [1,4,2,7,5]
----------------------第2次---------------------
取出lst[1] = 4; temp = lst[1]
lst[0] 不大于 temp, 不移动。
lst = [1,4,2,7,5]
----------------------第3次---------------------
取出lst[2] = 2; temp = lst[2]
lst[1] 大于 temp, lst[1]后移;
此时lst[2] = lst[1], 即lst[2] = 4。
lst[0] 不大于 temp, 不移动。
比较结束,将temp插入到列表中,lst[1] = temp。
lst = [1,2,4,7,5]
----------------------第4次---------------------
……
#插入排序示例代码
def insertsort(lst):
if lst:
if len(lst)<2:
return lst
L = lst[:]
for i in range(1, len(L)): #range()右边不闭合
temp = L[i]
j = i-1
while j>=0 and L[j] > temp:
L[j+1] = L[j]
j -= 1
if j<i-1:
L[j+1] = temp
return L
else:
return "List can't be none"
1.2 选择排序:从列表第一个元素开始,每一次取一个出来和该列表的后续元素比较,找到最小值,然后将最小值和列表的取出值对换即可。
选择排序示例
lst = [1,4,2,7,5]
----------------------第1次---------------------
取出lst[0] = 1; minindex = 0
和lst[1], lst[2], lst[3], lst[4]比较;
没有比lst[0]更小的值,则minindex=0,不交换,结束
lst = [1,4,2,7,5]
----------------------第2次---------------------
取出lst[1] = 4; minindex=1
和lst[2],lst[3],lst[4]比较;
得到最小值lst[2]的索引为minindex=2;
将lst[1]和lst[minindex]交换,结束。
lst = [1,2,4,7,5]
----------------------第3次---------------------
取出lst[2] = 4; minindex=2
和lst[3],lst[4]比较;
没有比lst[2]更小的值,则minindex还是等于2,不交换,结束
lst = [1,2,4,7,5]
----------------------第4次---------------------
……
def selectsort(lst):
if lst:
if len(lst)<2:
return lst
L = lst[:]
for i in range(len(L)-1):
min = i
for j in range(len(L)-1, i, -1):
if L[j] < L[min]:
min = j
if min != i:
temp = L[i]
L[i] = L[min]
L[min] = temp
return L
else:
return "List can't be none"
1.3 插入排序和选择排序性能对比:我们都知道插入排序和选择排序的平均时间复杂度都是

本文对比了插入排序和选择排序的性能,指出在随机序列中选择排序略优,但在有序序列中插入排序表现出色。接着,对比了归并排序和快速排序,分析了它们的平均和最坏情况下的时间复杂度。实验结果显示,快速排序通常优于归并排序,尤其是在有序列表中,但归并排序的性能更稳定。
&spm=1001.2101.3001.5002&articleId=108367734&d=1&t=3&u=b72ca77b3f2048218b7f20cd1a57554a)
1458

被折叠的 条评论
为什么被折叠?



