算法导论之选择排序法(selection——sort)

假设有数组A,使用选择排序法对该数组里的数据进行从小往大排序


算法思路:选择排序,第一次循环把最小的值和A0交换,第二次循环把剩下最小的值和A1交换,具体的逻辑伪代码如下:

  • 先进行输入数据的数组化(对应于Python)
# -*- coding: utf-8 -*-
# 例如输入的line是:1 5 3 4
# 对于字符串,先使用split方法按空格进行分割,结果为:['1', '5', '3', '4']
# 然后map函数将int函数迭代作用到每个元素上,最后用list使其成为一个整型数组
line = input()
A = list(map(int, line.split()))
print(A)


  • 进行相应数据的选择排序伪代码:
    for i=1 to A.length-1
        min=i 
        for j=i+1 to A.length
             if A[j]<A[min]
                min=j
         tem=A[min]
         A[min]=A[i]
    
         A[i]=tem
    //Exchange the data, but this data is not the formal coding but pseudocode ,
    need to transfer to specific code in different runtime environment 
    

    Loop invariant for the pseudocode will be:

    At the start of the each iteration of the outer for loop of lines 1-8, the subarray A[1..i−1]A[1..i−1] consists of i−1i−1 smallest elements of AA, sorted in increasing order.


  • run_code(python):

  • # -*- coding: utf-8 -*-
    # 例如输入的line是:1 5 3 4
    # 对于字符串,先使用split方法按空格进行分割,结果为:['1', '5', '3', '4']
    # 然后map函数将int函数迭代作用到每个元素上,最后用list使其成为一个整型数组
    line = input()
    A = list(map(int, line.split()))
    print(A)
    
    for i in range(len(A) - 1):
        # 将起始元素设为最小元素
        min_index = i
        # 第二层for表示最小元素和后面的元素逐个比较
        for j in range(i + 1, len(A)):
                 if A[j] <A[min_index]:
        # 如果当前元素比最小元素小,则把当前元素角标记为最小元素角标
                    min_index = j
             # 查找一遍后将最小元素与起始元素互换
        A[min_index], A[i] = A[i], A[min_index]
        
    print(A)

    运行结果:

  • For both the best-case (sorted array) and worst-case (reverse sorted array), the algorithm will anyway take one element at a time and compare it with all the other elements. So, the running times for both scenario will be Θ(n^{2}).

    https://atekihcan.github.io/CLRS/E02.02-02/

  • https://blog.csdn.net/newmemory/article/details/81427753

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值