It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
我知道python有很多内置函数,但我试着编写选择排序最小化内置函数,因为我试图理解算法我的输出不适合我的选择排序。感谢任何帮助!提前谢谢。

def selection_sort(list):
    for index in range(0, len(list)):
        for i in range(index,len(list)):
            iSmall = index

            if list[iSmall] > list[i]:
                iSmall = i
        list[index], list[iSmall] = list[iSmall], list[index]
    return list

if __name__ == '__main__':
    print selection_sort([5,2,4,6,1,3,])

最佳答案

iSmall = index不合适我没有提到所有评论提到的任何事情,这都是真的(截至本次编辑)。所以,在正确的位置使用iSmall = index的代码:

def selection_sort(list):
    for index in range(0, len(list)):
        iSmall = index
        for i in range(index,len(list)):
            if list[iSmall] > list[i]:
                iSmall = i
        list[index], list[iSmall] = list[iSmall], list[index]
    return list

if __name__ == '__main__':
    print selection_sort([5,2,4,6,1,3,])

换言之,您正在寻找一个最小的索引(并试图将其存储在iSMall中,但在循环iSmall的每个迭代中将index重置为for i in range(index,len(list)):。所以iSmall没有被正确设置,它总是被设置为index,除非在内环的最后一次迭代中它被更改为其他值。

关于python - 选择对没有内置插件的Python进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15753828/

10-10 09:54