首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环排序算法

循环排序算法
EN

Stack Overflow用户
提问于 2011-10-22 16:52:32
回答 1查看 6.1K关注 0票数 7

当我浏览互联网时,我发现有一种叫做循环排序的算法,它使得最少的内存writes.But,我无法找到算法anywhere.How来检测一个数组中是否有一个循环?有人能对这个算法给出一个完整的解释吗?

EN

回答 1

Stack Overflow用户

发布于 2016-04-10 02:52:20

如果任何人需要,这里有一个python实现

代码语言:javascript
复制
def cycleSort(vector):
    writes = 0

    # Loop through the vector to find cycles to rotate.
    for cycleStart, item in enumerate(vector):

        # Find where to put the item.
        pos = cycleStart
        for item2 in vector[cycleStart + 1:]:
            if item2 < item:
                pos += 1

        # If the item is already there, this is not a cycle.
        if pos == cycleStart:
            continue

        # Otherwise, put the item there or right after any duplicates.
        while item == vector[pos]:
            pos += 1
        vector[pos], item = item, vector[pos]
        writes += 1

        # Rotate the rest of the cycle.
        while pos != cycleStart:

            # Find where to put the item.
            pos = cycleStart
            for item2 in vector[cycleStart + 1:]:
                if item2 < item:
                    pos += 1

            # Put the item there or right after any duplicates.
            while item == vector[pos]:
                pos += 1
            vector[pos], item = item, vector[pos]
            writes += 1

    return writes


x = [0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6]
w = cycleSort(x) 
print w, x
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7858412

复制
相关文章

相似问题

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