#!/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))
二元選擇排序循環的次數更低,效率更高python