#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Date:2018-5-27 # Author:AreLIN #选择排序:每次只取一个最大或最小值的索引 import random a = [] count_swap = 0 count_iter = 0 #随机数列表 for _ in range(20): a.append(random.randrange(1,101)) print("my first list:\n{}".format(a)) for i in range(len(a)): maxindex = i for j in range(i+1,len(a)): count_iter += 1 if a[maxindex] < a[j]: maxindex = j if i != maxindex: a[maxindex],a[i] = a[i],a[maxindex] count_swap += 1 print("My end list:\n{} {} {}".format(a,count_iter,count_swap))
#二元选择排序:一次取两个值(最大最小)的索引
a = []
count_swap = 0
count_iter = 0
#随机数列表
for _ in range(20):
a.append(random.randrange(1,101))
print("my first list:\n{}".format(a))
for i in range(len(a)//2):
maxindex = i
minindex = -i - 1
minorign = minindex
for j in range(i+1,len(a)-i):
count_iter += 1
if a[maxindex] < a[j]:
maxindex = j
if a[minindex] > a[-j-1]:
minindex = -j - 1
print("{} {} ".format(maxindex,minindex),end=‘|‘)
if i != maxindex:
a[maxindex],a[i] = a[i],a[maxindex]
count_swap += 1
if (i == minindex) or (i == (len(a) + minindex)):
minindex = maxindex
if minorign != minindex:
a[minindex],a[minorign] = a[minorign],a[minindex]
count_swap += 1
print("The end list is:\n{},count_swap:{},count_iter:{}".format(a,count_swap,count_iter))
二元选择排序循环的次数更低,效率更高