python插入排序算法实例分析

yipeiwu_com5年前Python基础

本文实例讲述了python插入排序算法。分享给大家供大家参考。具体如下:

def insertsort(array): 
  for removed_index in range(1, len(array)): 
    removed_value = array[removed_index] 
    insert_index = removed_index 
    while insert_index > 0 and array[insert_index - 1] > removed_value: 
      array[insert_index] = array[insert_index - 1] 
      insert_index -= 1 
    array[insert_index] = removed_value

另外一个版本:

def insertsort(array): 
  for lastsortedelement in range(len(array)-1): 
    checked = lastsortedelement 
    while array[checked] > array[lastsortedelement + 1] and checked >= 0: 
      checked -= 1 
    #Insert the number into the correct position 
    array[checked+1], array[checked+2 : lastsortedelement+2] = array[lastsortedelement+1], array[checked+1 : lastsortedelement+1] 
  return array

希望本文所述对大家的Python程序设计有所帮助。

相关文章

深入解读Python解析XML的几种方式

深入解读Python解析XML的几种方式

在XML解析方面,Python贯彻了自己“开箱即用”(batteries included)的原则。在自带的标准库中,Python提供了大量可以用于处理XML语言的包和工具,数量之多,甚...

python email smtplib模块发送邮件代码实例

python email smtplib模块发送邮件代码实例

本例使用 QQ邮箱测试,需要打开 QQ邮箱的 smtp协议,获取授权码 代码内容如下: #!/usr/bin/env python # _*_ coding:utf-8 _*_ _...

python实现的登陆Discuz!论坛通用代码分享

代码如下: #coding:gbk import urllib2,urllib,cookielib,re ''' 通用的登陆DZ论坛 参数说明parms: userna...

python发送告警邮件脚本

python发送告警邮件脚本

python脚本为敏捷开发脚本,在zabbix监控也起到重要作用,以下是使用python脚本发送告警邮件配置方法。 脚本如下: #!/usr/bin/python #coding:u...

使用Python读写及压缩和解压缩文件的示例

读写文件 首先看一个例子: f = open('thefile.txt','w') #以写方式打开, try: f.write('wokao') finally: f.c...