码迷,mamicode.com
首页 > 编程语言 > 详细

python选择排序简单实现

时间:2018-05-28 11:45:06      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:7

#!/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选择排序简单实现

标签:7

原文地址:http://blog.51cto.com/12013190/2120940

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!