This article example describes the principle and usage of the insertion sort algorithm implemented in Python. Shared for your reference, as follows:
The basic operation of insertion sort is to insert a piece of data into the ordered data that has already been sorted, so as to obtain a new, number plus one ordered data, the algorithm is suitable for sorting a small amount of data, the time complexity is O(n^2). It is a stable sorting method
The insertion algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array except for the last element (to give the array one more space for the insertion), and the second part contains only this one element (i.e., the element to be inserted). After the first part has been sorted, this last element is then inserted into the first part, which is already sorted.
The basic idea of insertion sort is: each step will be a record to be sorted, according to the size of the key code value inserted in front of the file has been sorted in the appropriate location, until all inserted until the end.
The specific code is as follows:
#-*- coding: UTF-8 -*- import numpy as np def InsertSort(a): for i in xrange(1,): for j in xrange(i,0, -1): if a[j-1] > a[j]: a[j-1] , a[j] = a[j], a[j-1] else: break if __name__ == '__main__': a = (0, 10, size = 10) print "Before sorting..." print "---------------------------------------------------------------" print a print "---------------------------------------------------------------" print "After sorting..." InsertSort(a) print "---------------------------------------------------------------" print a print "---------------------------------------------------------------"
Run results:
Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Summary of Python encryption and decryption algorithms and techniques》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.