才学到一个新词,较为python,也就是python范儿的词:pythonic,哈哈。
直接选择排序(Straight Select Sorting) 也是一种简单的排序方法,它的基本思想是:第一次从R[0]~R[n-1]中选取最小值,与R[0]交换,第二次从R[1]~R[n-1]中选取最小值,与R[1]交换,....,第i次从R[i-1]~R[n-1]中选取最小值,与R[i-1]交换,.....,第n-1次从R[n-2]~R[n-1]中选取最小值,与R[n-2]交换,总共通过n-1次,得到一个按排序码从小到大排列的有序序列。
一般写法:
def select_sort2(sque):
n = len(sque)
for i in range(n):
for j in range(i + 1, n):
if sque[i] > sque[j]:
sque[i], sque[j] = sque[j], sque[i]
a=[23,34,6,6542,54,654,43,5,7,657,4,3,4,3,7,6,65,3]
select_sort2(a)
print(a)
较为python的写法(暂且不论执行效率和资源消耗,哈哈)
def select_sort1(sque):
n=len(sque)
for i in range(n):
index_min=sque.index(min(sque[i:]),i)
sque[i],sque[index_min]=sque[index_min],sque[i]
a=[23,34,6,6542,54,654,43,5,7,657,4,3,4,3,7,6,65,3]
select_sort1(a)
print(a)
效率:
经对9000个正整数测试,用第二种写法select_sort1,比第一种select_sotr2效率高大约5倍,效果让人惊讶。