Insert sorting in PHP

Source: Internet
Author: User

The basic operation of insert sorting is to insert a data to an ordered data that has already been sorted, so as to get a new ordered data with a number plus one.

AlgorithmDescription:

The sequence starts from the first element. This element can be considered to have been sorted. The sequence is used to retrieve the next element. In the sequence of sorted elements, the sequence is scanned forward. If this element is sorted) if the value is greater than the new element, move the element to the next position, repeat Step 3, until the sorted element is found to be less than or equal to the position where the new element is located. Then, insert the new element to the next position, and repeat Step 2.
<? PHP  $ Arr = Array (, 0, 5,-, 15 );  Function Insertsort (& $ Arr  ){  //  First, the first subscript is 0 by default.          For ($ I = 1; $ I < Count ( $ Arr ); $ I ++ ){  //  Determine the number of inserted comparisons              $ Insertval = $ Arr [ $ I  ];  //  Determine the number comparison with the previous comparison              $ Insertindex =$ I -1 ;  //  No location found              While ( $ Insertindex > = 0 && $ Insertval < $ Arr [ $ Insertindex  ]) {  //  Move the number behind                  $ Arr [ $ Insertindex + 1] =$ Arr [ $ Insertindex  ];  $ Insertindex -- ;}  //  Insert (locate $ insertval)          $ Arr [ $ Insertindex + 1] = $ Insertval  ;} Insertsort (  $ Arr  );  Print_r ($ Arr  ); ?>

 

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.