Python 实现选择排序

来源:互联网 发布:ubuntu iso安装教程 编辑:程序博客网 时间:2024/06/06 15:36
# Sorts a sequence in ascending order using the selection sort algorithmdef selectionSort(theSeq):    n = len(theSeq)    for i in range(n-1):        # Assume the ith element is the smallest        smallNdx = i        # Determine if any other element contains a smaller value        for j in range(i+1, n):            if theSeq[j] < theSeq[smallNdx]:                smallNdx = j        # Swap the ith value and smallNdx value only if the smallest value is        # not already in its proper position. Some implementations omit testing        # the condition and always swap the two values        if smallNdx != i:            tmp = theSeq[i]            theSeq[i] = theSeq[smallNdx]            theSeq[smallNdx] = tmp

In [2]: theSeq = [3,7,5,2,9,10]In [3]: selectionSort(theSeq)In [4]: theSeqOut[4]: [2, 3, 5, 7, 9, 10]

0 0
原创粉丝点击