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