The Selection Sort

A selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location.
As with a bubble sort, after the first pass, the largest item is in the correct place.
After the second pass, the next largest is in place. This process continues and requires n−1 passes to sort n items, since the final item must be in place after the (n−1) st pass.

def selectionSort(alist):
    for fillslot in range (len(alist)-1,0,-1):
        #從後往前循環
        #[8,7,6,5,4,3,2,1]#列
        positionOfMax=0#最大值的位置爲0

        for location in range(1,fillslot+1):#行,內部查找
            if alist[location]>alist[positionOfMax]:
                #找到最大值,然後最大值的位置爲找到數字的位置
                positionOfMax=location
        #對調
        temp = alist[fillslot]
        alist[fillslot] = alist[positionOfMax]
        alist[positionOfMax] = temp

alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)

1)循環第一次,先找到最大/最小值,把最小值放在第一位,或者最大的放最後。
2)循環第二次,找到第二小的數字,放在最小值的後面的數字對調
3)以此類推

def select_sort(ary):
    n = len(ary)
    for i in range(0,n):
        min = i                             #最小元素下標標記
        for j in range(i+1,n):
            if ary[j] < ary[min] :
                min = j                     #找到最小值的下標
        ary[min],ary[i] = ary[i],ary[min]   #交換兩者
    return ary

Q-49: Suppose you have the following list of numbers to sort: [11, 7, 12, 14, 19, 1, 6, 18, 8, 20] which list represents the partially sorted list after three complete passes of selection sort?
[11, 7, 12, 14, 8, 1, 6, 18, 19, 20]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章