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中数据集划分函数StratifiedShuffleSplit的使用详解

对python中数据集划分函数StratifiedShuffleSplit的使用详解

文章开始先讲下交叉验证,这个概念同样适用于这个划分函数 1.交叉验证(Cross-validation) 交叉验证是指在给定的建模样本中,拿出其中的大部分样本进行模型训练,生成模型,留小...

python 命令行传入参数实现解析

python 命令行传入参数实现解析

创建 test.py 文件,代码如下: #!/usr/bin/python # -*- coding: gbk -*- import sys print sys.argv if __...

python回调函数的使用方法

有两种类型的回调函数:复制代码 代码如下:blocking callbacks (also known as synchronous callbacks or just callback...

Django视图之ORM数据库查询操作API的实例

查询表记录 查询相关API 操作:models.表名.objects.方法() <BR>all(): 查询所有结果 filter(**kwargs): 它...

详解Python中的相对导入和绝对导入

前言 Python 相对导入与绝对导入,这两个概念是相对于包内导入而言的。包内导入即是包内的模块导入包内部的模块。 Python import 的搜索路径 在当前目录下搜索该模块...