我们首先找到其中最大的元素,并将其放在 n <script id="MathJax-Element-11" type="math/tex">n</script> 的位置(也即交换),然后继续排序剩下的元素:
递归版:
def sel_sort_rec(seq, n):
if n == 0: return
max_j = n
for i in range(n):
if seq[i] > seq[max_j]:
max_j = i
seq[n], seq[max_j] = seq[max_j], seq[n]
sel_sort_rec(seq, n-1)
迭代版:
def sel_sort(seq):
n = len(seq)
for i in range(n-1, 0, -1):
max_j = i
for j in range(i):
if seq[j] > seq[max_j]:
max_j = j
seq[i], seq[max_j] = seq[max_j], seq[i]