[英]Number of comparisons in insertion sort
In this program, I want to calculate the number of data comparisons in the insertion sort, but my code is not working as I expected. 在此程序中,我想计算插入排序中的数据比较次数,但是我的代码无法正常工作。
def insertionSort(list):
numOfComp = 0
for i in range(1,len(list)):
value = list[i]
j = i - 1
while j>=0:
if value < list[j]:
list[j+1] = list[j]
list[j] = value
j = j - 1
numOfComp += 1
if value >= list[j]:
numOfComp += 1
j = j - 1
else:
break
print("Number of data comparisons:",numOfComp)
print("Sorted list:",list)
the problem is 问题是
if value >= list[j]:
numOfComp += 1
j = j - 1
If value >= list[j]
you can and should simply exit your while loop and stop further comarisons 如果
value >= list[j]
您可以并且应该简单地退出while循环并停止进一步的比较
Also you are repeating the comparisons twice See the following refined code 另外,您要重复两次比较,请参见以下精炼代码
def insertionSort(list):
numOfComp = 0
for i in range(1,len(list)):
value = list[i]
j = i - 1
while j>=0:
if value<list[j]:
flag=True
else :
flag=False
numOfComp += 1
if flag:
list[j+1] = list[j]
list[j] = value
j = j - 1
else:
break
print("Number of data comparisons:",numOfComp)
print("Sorted list:",list)
Don't forget that loop header executed +1 more then the loop body, which we call the exit-condition, take this example: 不要忘了循环头执行的次数比循环主体(我们称为退出条件)多执行+1,请看以下示例:
S = 0;
for(int i = 0; i < 5; i++) {
S++;
}
The S++ runs 5 times , however the i < 5 runs 6 times, the last one is to check if i < 5, will find the false and exit the loop. S ++运行5次 ,但是i <5运行6次,最后一个是检查i <5是否会发现错误并退出循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.