-
-
/** - * Insertion sort
- * @param Array $a unordered set
- * @return Array ordered set
- */
- function insertSort($a) {
- $temp;
- $i;
- $j;
- $size_a = count($ a);
- #Start from the second element
- for ($i = 1; $i < $size_a; $i++) {
- if ($a[$i] < $a[$i-1]) {
- $j = $i; # Save the position of the current element
- $temp = $a[$i]; # The value of the current element
-
- # Compare the element on the left, if it finds one smaller than itself, move the element to the right , otherwise insert the element to the current position
- while($j>0 && $temp<$a[$j-1]) {
- $a[$j] = $a[$j-1];
- $j-- ;
- }
# Insert element
- $a[$j] = $temp;
- }
- }
- return $a;
- }
- /**
- * Get random number
- * @param Integer $size quantity
- * @return Integer
- */
- function randomNumber ($size = 10) {
- $rand = array();
- srand(time(NULL));
- for ($i = 0; $i < $size; $i++) {
- array_push($rand, mt_rand (0,1000));
- }
- return $rand;
- }
-
- $a = randomNumber();
- echo sprintf("Unsorted list %sn", implode(" ", $a));
- echo sprintf( "Sorted list %sn", implode(" ", insertSort($a)));
-
Copy code
php insertion sort implementation code
Insertion sort:
Insert a piece of data into the sorted sorted data to obtain a new sorted 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
Example:
-
-
$arr =array(123,0,5,-1,4,15); - function insertSort(&$arr){
- //default first A number with a subscript of 0 is an arranged number
- for($i=1;$i//Determine the number for insertion and comparison
- $insertVal=$arr[$ i];
- //Confirm and compare with the previously compared number
- $insertIndex=$i-1;
//Indicates that the position is not found
- 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);
- ?>
Copy code
|