Insert sorting-Python and PHP implementation versions, and sorting-pythonphp implementation
Insert and sort Python implementation
Import randoma = [random. randint (1,999) for x in range ()] # directly Insert the Sorting Algorithm def insertionSort (a): for I in range (1, len ()): # if the element whose subscript is I is less than the element whose subscript is I-1, place the element whose subscript is I in the proper position if a [I] <a [I-1]: tmp = a [I] j = I-1 # Find the proper location of a [I, and move the elements from a [I-1] to a [I] to the new position in sequence while j> = 0 and tmp <a [j]: a [j + 1] = a [j] j = J-1 # place a [I] in the new location a [j + 1] = tmpinsertionSort (a) print ()
Insert sorting PHP implementation
<? Php // generate the array to be sorted $ a = []; for ($ I = 0; $ I <36; $ I ++) {array_push ($, mt_rand (1,999);} shuffle ($ ); /*** insert sorting insertion sort * @ param [type] $ a reference to the array to be sorted * @ return null */function insertionSort (& $) {for ($ I = 1; $ I <count ($ a); $ I ++) {// If the element whose subscript is I is smaller than the element whose subscript is I-1, place the element whose subscript is I in the proper position if ($ a [$ I] <$ a [$ I-1]) {$ tmp = $ a [$ I]; // find the appropriate location for a [I] and move the elements from a [I-1] to a [I] to the new location in turn for ($ j = $ I-1; $ j> = 0 & $ tmp <$ a [$ j]; $ j --) $ a [$ j + 1] = $ a [$ j]; // place a [I] to the new location $ a [$ j + 1] = $ tmp ;}} insertionSort ($ a); var_dump ($ );
Insert sorting time complexity analysis
The time complexity of inserting a sorting algorithm is O (n2), but the insert sorting method has better performance than bubble and select sorting.