PHP four basic algorithm----insertion sorting method

Source: Internet
Author: User

3. Insert Sort method
Insert Sort idea: Inserts the element that will be sorted into the specified position of the array that has assumed the sort number.

Code:

function Insert_sort ($arr) {
Distinguish which part is already sorted
Which part is not sorted
Find one of the elements that needs to be sorted
This element starts with the second element and the last element is the one that needs to be sorted.
You can sign it with a loop.
I loop control every time an element needs to be inserted, once the element that needs to be inserted is controlled,
Indirectly has divided the array into 2 parts, the subscript is less than the current (left), is a sorted sequence
For ($i =1, $len =count ($arr), $i < $len; $i + +) {
Gets the value of the element that is currently required to be compared.
$tmp = $arr [$i];
Inner loop control comparison and insertion
for ($j = $i-1; $j >=0; $j-) {
$arr [$i];//the element to be inserted; $arr [$j];//elements that need to be compared
if ($tmp < $arr [$j]) {
Find the inserted element to be small, swap position
Swap the elements behind with the previous elements
$arr [$j +1] = $arr [$j];
Set the previous number to the current number that needs to be exchanged
$arr [$j] = $tmp;
} else {
If you encounter an element that does not need to be moved
Since the array is already sorted, the preceding one does not need to be compared again.
Break
}
}
}
Insert this element into a sequence that is already sorted.
Return
return $arr;
}

PHP four basic algorithm----insertion sorting method

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.