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);
?>