[数据结构][Python]递归版插入排序和选择排序

    xiaoxiao2025-03-25  37

    插入排序递归版:

    def ins_sort_rec(seq,i): if i==0:return ins_sort_rec(seq,i-1) j=i while j>0 and seq[j-1]>seq[j]: seq[j-1], seq[j]= seq[j],seq[j-1] j-=1

    插入排序非递归版:

    def ins_sort(seq): for i in range(1,len(seq)): j = i while j>0 and seq[j-1]>seq[j]: seq[j - 1], seq[j] = seq[j], seq[j - 1] j -= 1

    递归版选择排序:

    def sel_sort_rec(seq,i): if i==0:return 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] sel_sort_rec(seq,i-1)

    非递归版选择排序

    def sel_sort(seq): for i in range(len(seq)-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]
    最新回复(0)