Selection Sort

本文介绍了一种改进版的冒泡排序——选择排序算法,并通过一个示例程序详细展示了其工作原理。选择排序通过每次遍历只进行一次交换来提高效率,每完成一次遍历则将当前未排序部分的最大元素放置到正确的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

def selectionSort(alist):
    a = len(alist)-1
    while a > 0:
        flag = 0
        for i in range(0,a+1):
            if alist[i] > alist[flag]:
                flag = i
        alist[a], alist[flag] = alist[flag], alist[a]
        a -=1

alist = [1,20,17,2,33,11111,454,3244,12222222]
selectionSort(alist)
print(alist)

The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, 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−1n−1passes to sort n items, since the final item must be in place after the (n−1)(n−1) st pass.

Figure 3 shows the entire sorting process. On each pass, the largest remaining item is selected and then placed in its proper location. The first pass places 93, the second pass places 77, the third places 55, and so on.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值