How to implement insert sort in PHP? _php Tutorials

Source: Internet
Author: User
The basic operation of inserting a sort is to insert a piece of data into the ordered data that is already sorted, thus obtaining a new, sequential data with a number plus one.

Algorithm Description:

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

⒉ takes the next element and scans the sequence of elements that have been sorted from backward forward

⒊ if the element (sorted) 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 of the new element

⒌ inserting new elements into the next position

⒍ Repeat step 2

Copy the Code code as follows:

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

Function Insertsort (& $arr) {

First, default to the number of 0 is the number of rows
for ($i =1; $i<>
Determining the number of insert comparisons
$insertVal = $arr [$i];
Determine the number of comparisons 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);
?>

http://www.bkjia.com/PHPjc/326657.html www.bkjia.com true http://www.bkjia.com/PHPjc/326657.html techarticle the basic operation of inserting a sort is to insert a piece of data into the ordered data that is already sorted, thus obtaining a new, sequential data with a number plus one. Algorithm Description: ⒈ from the first ...

  • 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.