圆月山庄资源网 Design By www.vgjia.com

本文所述的Python实现冒泡,插入,选择排序简单实例比较适合Python初学者从基础开始学习数据结构和算法,示例简单易懂,具体代码如下:

# -*- coding: cp936 -*-
#python插入排序
def insertSort(a):
  for i in range(len(a)-1):
    #print a,i 
    for j in range(i+1,len(a)):
      if a[i]>a[j]:
        temp = a[i]
        a[i] = a[j]
        a[j] = temp
  return a

#Python的冒泡排序  
def bubbleSort(alist):
  for passnum in range(len(alist)-1,0,-1):
    #print alist,passnum
    for i in range(passnum):
      if alist[i]>alist[i+1]:
        temp = alist[i]
        alist[i] = alist[i+1]
        alist[i+1] = temp
  return alist

#Python的选择排序 
def selectionSort(alist):
  for i in range(len(alist)-1,0,-1):
    maxone = 0
    for j in range(1,i+1):
      if alist[j]>alist[maxone]:
        maxone = j
    temp = alist[i] 
    alist[i] = alist[maxone]
    alist[maxone] = temp 
  return alist

alist = [54,26,93,17,77,31,44,55,20]
#print bubbleSort(alist)
alist = [54,26,93,17,77,31,44,55,20]
print selectionSort(alist)

感兴趣的朋友可以动手测试一下本文实例,相信会有新的收获。

标签:
Python,排序

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com