Home > Backend Development > Python Tutorial > Example of direct insertion sort algorithm implemented in Python

Example of direct insertion sort algorithm implemented in Python

不言
Release: 2018-05-02 15:49:52
Original
1751 people have browsed it

This article mainly introduces the direct insertion sorting algorithm implemented in Python, and analyzes the definition and usage of the Python direct insertion sorting algorithm in the form of examples. The code is equipped with more detailed comments for easy understanding. Friends in need can refer to it. Next

The example in this article describes the direct insertion sort algorithm implemented in Python. Share it with everyone for your reference, the details are as follows:

# -*- coding:utf-8 -*-
'''直接插入的python实现
  时间复杂度O(n**2) 空间复杂度O(1) 稳定
思想:先将前两个元素排序,第三个元素插入前面已排好序列,
    后面的元素依次插入之前已经排好序的序列
'''
author = 'Leo Howell'
L = [89,67,56,45,34,23,1]
def direct_insert_sort(numbers):
  for i in range(1,len(numbers)):
    #temp变量指向尚未排好序元素(从第二个开始)
    temp = numbers[i]
    #j指向前一个元素的下标
    j = i-1
    #temp与前一个元素比较,若temp较小则前一元素后移,j自减,继续比较
    while j>=0 and temp<numbers[j]:
      numbers[j+1]=numbers[j]
      j = j-1
    #temp所指向元素的最终位置
    numbers[j+1] = temp
if __name__==&#39;__main__&#39;:
  direct_insert_sort(L)
  print L
Copy after login

Running results:

Related recommendations:

Detailed explanation of binary search and quick sorting examples in python

The above is the detailed content of Example of direct insertion sort algorithm implemented in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template