How do I implement insert ordering in PHP? _php instance

Source: Internet
Author: User

The basic operation of inserting a sort is to insert a data into the ordered data, so as to get a new, number plus one ordered data.

Algorithm Description:

⒈ starting with the first element, the element can be considered to have been sorted

⒉ takes out the next element and scans the sequence of elements that are already sorted from the back forward

⒊ if the element (sorted) is greater than the new element, move the element to the next position

⒋ Repeat step 3 until you find the location of the sorted element less than or equal to the new element

⒌ inserts a new element into the next location

⒍ Repeat step 2

Copy Code code as follows:

<?php

$arr =array (123,0,5,-1,4,15);

Function Insertsort (& $arr) {

Default first subscript 0 is the number of rows
for ($i =1; $i <count ($arr); $i + +) {
Determine the number of insert comparisons
$insertVal = $arr [$i];
Determine the number compared to the previous comparison
$insertIndex = $i-1;

Indicates no location found
while ($insertIndex >=0 && $insertVal < $arr [$insertIndex]) {

Move the number back
$arr [$insertIndex +1]= $arr [$insertIndex];
$insertIndex--;
}

Insert (Find a location for $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.