Insert Sort PHP Version

Source: Internet
Author: User

function Insertsort (array $container)
{
$count = count ($container);
for ($i = 1; $i < $count; $i + +) {
$temp = $container [$i];
$j = $i-1;
Init
while ($container [$j] > $temp) {
$container [$j +1] = $container [$j];
$container [$j] = $temp;
$j--;
Print_r ($container);
if ($j < 0) break;
}

}
return $container;
}
Print_r (Insertsort ([3, 12, 42, 1, 24, 5, 346, 7]));

$container of output when printing out i=3

Array

(    [0] => 3    [1] => 12    [2] => 1    [3] => 42    [4] => 24    [5] => 5    [6] => 346    [7] => 7)Array(    [0] => 3    [1] => 1    [2] => 12    [3] => 42    [4] => 24    [5] => 5    [6] => 346    [7] => 7)Array(    [0] => 1    [1] => 3    [2] => 12    [3] => 42    [4] => 24    [5] => 5    [6] => 346    [7] => 7)Thus see the array[3] 1, step-by-step move to array[0]. When array[2] > array[3] 1 o'clock into the while loop, swap position,

Array

(    [0] => 3    [1] => 12    [2] => 1    [3] => 42    [4] => 24    [5] => 5    [6] => 346    [7] => 7)Then J-1=1, continue to judge when Array[1] of the 1 > array[2] into the while loop, swap position,Array(    [0] => 3    [1] => 1    [2] => 12    [3] => 42    [4] => 24    [5] => 5    [6] => 346    [7] => 7)Immediately j-1=0, continue to judge when Array[0] 3 > array[1] 1 into the while loop, swap position,Array(    [0] => 1    [1] => 3    [2] => 12    [3] => 42    [4] => 24    [5] => 5    [6] => 346    [7] => 7)The j-1=-1,break exits while. I=4 continue to circulate; get the final result:Array(    [0] => 1    [1] => 3    [2] => 12    [3] => 42    [4] => 24    [5] => 5    [6] => 346    [7] => 7)

Insert Sort PHP Version

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.