Insert sorting-Python and PHP implementation versions, and sorting-pythonphp implementation

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.