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程序设计有所帮助。

相关文章

Zabbix实现微信报警功能

Zabbix实现微信报警功能

一、 申请企业微信账号,申请地址 https://qy.weixin.qq.com/ 二、 登陆企业微信账 图一 图二 2、添加微信账号  图一 图二 完成以上步骤...

对python中的six.moves模块的下载函数urlretrieve详解

对python中的six.moves模块的下载函数urlretrieve详解

实验环境:windows 7,anaconda 3(python 3.5),tensorflow(gpu/cpu) 函数介绍:所用函数为six.moves下的urllib中的函数,调用如...

python GUI图形化编程wxpython的使用

python GUI图形化编程wxpython的使用

一、python gui(图形化)模块介绍:   Tkinter :是python最简单的图形化模块,总共只有14种组建   Pyqt :是python最复杂也是使用最广泛的图形化   ...

使用python 打开文件并做匹配处理的实例

如下所示: import os import re import string file = open("data2.txt") p1 = re.compile(r"^(\d...

python pandas dataframe 按列或者按行合并的方法

concat 与其说是连接,更准确的说是拼接。就是把两个表直接合在一起。于是有一个突出的问题,是横向拼接还是纵向拼接,所以concat 函数的关键参数是axis 。 函数的具体参数是:...