PHP direct insertion sorting

Source: Internet
Author: User
  • Generally, the time complexity of direct insertion sorting is O (n ^ 2), but when the series are basically ordered, the time complexity will be improved to O (N)
1 <? PHP 2 # specify that all part of the array elements move one 3 function move (array $ arr, $ start = NULL, $ end = NULL) {4 If (! Isset ($ start) | $ start <0) $ start = 0; 5 If (! Isset ($ end) | $ end> = count ($ ARR) $ end = count ($ ARR)-2; # Finally, you can only select 6 for ($ I = $ end; $ I >=$ start; $ I --) {7 $ arr [$ I + 1] = $ arr [$ I]; 8} 9 return $ arr; 10} 11 12 # insert sorting, implement 13 function insertsort (array $ ARR) {14 for ($ I = 1; $ I <count ($ ARR); $ I ++) using the same Array move-Back Method) {# unordered array, starting from the second element 15 $ insertele = $ arr [$ I]; # element to be inserted 16 for ($ J = 0; $ j <$ I; $ J ++) {# sorted array, starting from the first element 17 if ($ arr [$ J]> $ arr [$ I]) {# sort by Ascending Order 18 $ ar R = move ($ arr, $ J, $ I-1 ); # First move all the elements in the sorted array that are larger than the elements to be inserted, and then move one digit 19 $ arr [$ J] = $ insertele; # insert 20 break of the element to be inserted; 21} 22} 23} 24 return $ arr; 25} 26 27 $ arr = array (5, 1, 7, 4, 6, 2 ); 28 $ arr = insertsort ($ ARR); 29 print_r ($ ARR); 30?>

Output:

Array ([0] => 1 [1] => 2 [2] => 4 [3] => 5 [4] => 6 [5] => 7)

The sorting process is as follows. Red indicates the sorted part.

 

 

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.