您的位置:首页 > 其它

The Selection Sort

2015-11-08 05:59 344 查看
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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: