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

简单算法

时间:2018-03-17 12:17:24      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:__name__   class   strong   min   font   lis   lock   ble   end   

冒泡排序:(bubble sort)

 1 import time
 2 def bubble_sort(a_list):
 3     n = len(a_list)
 4     for j in range(0,n-1):
      count = 0
5 for i in range(0,n-1-j): 6 if(a_list[i]>a_list[i+1]): 7 a_list[i],a_list[i+1] = a_list[i+1],a_list[i]
           count += 1
      if count == 0:
        return
8 print(a_list) 9 if __name__==__main__: 10 start_time = time.clock() 11 a_list = [12,35,15,6,4,8,48,54,21,65,45] 12 print(a_list) 13 bubble_sort(a_list) 14 end_time = time.clock() 15 use_time = end_time-start_time 16 print(use_time)
1 [12, 35, 15, 6, 4, 8, 48, 54, 21, 65, 45]
2 [4, 6, 8, 12, 15, 21, 35, 45, 48, 54, 65]
3 4.2666704592626304e-05

选择排序(select sort):

 1 def select_sort (a_list):
 2     n = len(a_list)
 3     for j in range(0,n-1):
 4         min = j
 5         for i in range(j+1, n):
 6             if a_list[min]>a_list[i]:
 7                 min = i
 8         a_list[j] , a_list[min] = a_list[min],a_list[j]
 9     print(a_list)
10 if __name__ and __main__:
11     a_list= [12, 35, 15, 6, 4, 8, 48, 54, 21, 65, 45]
12     print(a_list)
13     select_sort(a_list)
1 [12, 35, 15, 6, 4, 8, 48, 54, 21, 65, 45]
2 [4, 6, 8, 12, 15, 21, 35, 45, 48, 54, 65]

 

简单算法

标签:__name__   class   strong   min   font   lis   lock   ble   end   

原文地址:https://www.cnblogs.com/eu-feng/p/8588169.html

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