PHP inserts the sort implementation code

  • 2020-05-30 19:42:41
  • OfStack

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: