How to implement insertion sort with PHP?

  • 2020-06-01 08:25:25
  • OfStack

The basic operation of insertion sort is to insert 1 data into the already sorted ordered data, so as to get 1 new ordered data with 1 number.

Algorithm description:

A. starts with the first element, which can be considered sorted

If the element (sorted) is greater than the new element, move the element to the next 1

4. Repeat step 3 until the sorted element is found to be less than or equal to the new element

⒌ insert a new element to the next 1 location

Repeat step 2 before the pictures


<?php
$arr =array(123,0,5,-1,4,15);
function insertSort(&$arr){
// By default the first 1 A subscript for 0 Theta is the sorted number 
for($i=1;$i<count($arr);$i++){
// Determine the number of insert comparisons 
$insertVal=$arr[$i];
// Determine the comparison with the previous number 
$insertIndex=$i-1;

// No location was found 
while($insertIndex>=0 && $insertVal<$arr[$insertIndex]){
// Counting backwards 
$arr[$insertIndex+1]=$arr[$insertIndex];
$insertIndex--;
}
// insert ( to $insertval Got the location. )
$arr[$insertIndex+1] = $insertVal;
}
}
insertSort($arr);
print_r($arr);
?>


Related articles: