Home >Backend Development >PHP Tutorial >How to implement insertion sort using PHP? _PHP Tutorial
The basic operation of insertion sort is to insert a piece of data into the already sorted ordered data, thereby obtaining a new ordered data with the number plus one.
Algorithm description:
⒈ Starting from the first element, the element can be considered to have been sorted
⒉ Take out the next element and scan from back to front in the sorted element sequence
⒊ If the element (sorted) is larger than the new element, move the element to the next position
⒋ Repeat step 3 until you find the position where the sorted element is less than or equal to the new element
⒌ Insert the new element into the next position
⒍ Repeat step 2
$arr =array(123,0,5,-1,4,15);
function insertSort(&$arr){
//First default that the first number with subscript 0 is the arranged number
for($i=1;$i
$insertVal=$arr[$i];
//Confirm and compare with the previous compared number
$insertIndex=$i-1;
//Indicates none Find the position
while($insertIndex>=0 && $insertVal<$arr[$insertIndex]){
//Move the number back
$arr[$insertIndex+1]=$arr[$insertIndex];
$insertIndex--;
}
//Insert (find the position for $insertval)
$arr[$insertIndex+1] = $insertVal;
}
}
insertSort($arr);
print_r($arr);
?>