首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入排序上的计数比较

插入排序上的计数比较
EN

Stack Overflow用户
提问于 2017-10-27 03:52:37
回答 2查看 1.5K关注 0票数 0

我很难弄清楚如何为我的插入排序创建一个计数器,在这个计数器中,它计算插入排序进行的比较次数。

简而言之,我想知道如何计算所有的比较,即使是while循环和for循环中的比较。

代码语言:javascript
复制
import random

class sorting:

    alist = []
    # 10 random numbers between 10 and 70
    for i in range(10):
        # integer random numbers between 10 and 70
        n = random.randint(10, 70)
        alist.append(n)
    print(alist)

    def insertionSort(alist,):
        for index in range(1, len(alist)):

            currentvalue = alist[index]
            position = index

            while position > 0 and alist[position - 1] > currentvalue:
                alist[position] = alist[position - 1]
                position = position - 1

            alist[position] = currentvalue

    insertionSort(alist)
EN

回答 2

Stack Overflow用户

发布于 2017-10-27 04:14:17

这是正确的吗?

代码语言:javascript
复制
import random

类排序:

代码语言:javascript
复制
alist = []
# 10 random numbers between 10 and 70
for i in range(2):
    # integer random numbers between 10 and 70
    n = random.randint(10, 70)
    alist.append(n)
print(alist)



def insertionSort(alist):
    count = 0
    for index in range(1, len(alist)):

        currentvalue = alist[index]

        position = index

        while position > 0 and alist[position - 1] > currentvalue:
            alist[position] = alist[position - 1]
            position = position - 1
            count +=1


        alist[position] = currentvalue
    count += 1
    print(count)


insertionSort(alist)
票数 0
EN

Stack Overflow用户

发布于 2017-10-27 04:16:17

您可以添加一个计数器,并按照注释中的建议保持其计数。最终代码如下所示

代码语言:javascript
复制
import random

class sorting:

alist = []
# 10 random numbers between 10 and 70
for i in range(10):
    # integer random numbers between 10 and 70
    n = random.randint(10, 70)
    alist.append(n)
print(alist)

def insertionSort(alist,):
    counter=0
    for index in range(1, len(alist)):

        currentvalue = alist[index]
        position = index
        counter +=2  # For the case postion <0 ........
        while position > 0 and alist[position - 1] > currentvalue:
            counter +=2
            alist[position] = alist[position - 1]
            position = position - 1

        alist[position] = currentvalue
    print(counter)
insertionSort(alist)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46962699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档