python插入排序算法实例分析

yipeiwu_com6年前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多线程案例之多任务copy文件完整实例

python多线程案例之多任务copy文件完整实例

本文实例讲述了python多线程案例之多任务copy文件。分享给大家供大家参考,具体如下: import os import multiprocessing def copy_fil...

Python3 venv搭建轻量级虚拟环境的步骤(图文)

Python3 venv搭建轻量级虚拟环境的步骤(图文)

今天先聊一聊在windows/mac iOS系统下用venv搭建python轻量级虚拟环境的问题。 使用venv搭建的虚拟环境同virtualenv搭建的虚拟环境,即venv可替代vir...

Python实现微信翻译机器人的方法

Python实现微信翻译机器人的方法

相信大家在日常学习或者是阅读英文文章的过程中,难免会出现几个不认识的单词,或者想快速翻译某段英文的意思。 今天,利用Python爬虫等知识,教大家打造一个微信下的翻译小助手。好吧,开始干...

利用python-docx模块写批量生日邀请函

利用python-docx模块写批量生日邀请函

利用python-docx模块,写批量生日邀请函 有关python-docx的使用方法,可以参考官方的API文档。这里使用了其中的一些基本功能,来完成一个简单的任务:为参加聚会的好友,每...

python添加菜单图文讲解

python添加菜单图文讲解

分享一个基于tkinter的菜单程序添加操作,希望对需要的朋友有帮助。 打开python集成开发环境,使用 from tkinter import Tk from tkinter im...