假设有数组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 Θ(
).
-
https://blog.youkuaiyun.com/newmemory/article/details/81427753