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

python 排序算法

时间:2016-08-13 11:22:16      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

1、冒泡法(直接交换元素)

 1 def bubble_sort(a_list):
 2     a_len = len(a_list)-1
 3     while a_len > 0:
 4         for i in range(a_len):
 5             if a_list[i] >a_list[i+1]:
 6                 a_list[i],a_list[i+1] = a_list[i+1],a_list[i]
 7 
 8         a_len -=1
 9 
10 if __name__ == __main__:
11     a_list=[20,40,30,90,50,80,70,60,110,100]
12     bubble_sort(a_list)
13     print(a_list)

2、选择排序法(交换元素位置下表,选出最大后交换元素)

 1 def selection_sort(a_list):
 2     alen = len(a_list)
 3     while alen >0:
 4         postion = 0
 5         for i in range(1,alen):
 6             if a_list[i] >a_list[postion]:
 7                 postion = i     #选择最大元素位置下标
 8             a_list[postion],a_list[alen-1] = a_list[alen-1],a_list[postion]
 9         alen -= 1
10 
11 if __name__ == __main__:
12     a_list=[20,40,30,90,50,80,70,60,110,100]
13     selection_sort(a_list)
14     print(a_list)

 3、插入排序法 将数据插入到排好的序列中。稳定的排序方法。

1 def Insert_sort(alist):
2     length = len(alist)
3     for index in range(1,length):
4         p = index 
5         while p >0:
6             if alist[p] < alist[p-1]:
7                 alist[p],alist[p-1] = alist[p-1],alist[p]
8             p -= 1
9     return alist 

 

python 排序算法

标签:

原文地址:http://www.cnblogs.com/hb91/p/5762743.html

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