1. Bubble Sort Algorithm
Process:
1. Iterate through the array, each 22 adjacent elements for comparison, such as $a[$i]> $a [$i +1] then swap position, each comparison to eliminate a reverse order.
2. After each cycle, the next time you need to cycle the number of times reduced by 1.
<?php
//bubble sort
$arr = Createarr;
Printarr ($arr);
Popsort ($arr);
Printarr ($arr);
function Createarr ($num =10) {
$arr = array ();
For ($i =0 $i < $num; $i + +) {
Array_push ($arr, Mt_rand (0,999));
}
return $arr;
}
function Printarr ($arr) {
echo ' arr: '. Implode (', ', $arr). ' <br> ';
}
Function Popsort (& $arr) {
for ($i =0, $length =count ($arr)-1; $i < $length; $i + +) {for
($j =0; $j <$ length-$i; $j + +) {
if ($arr [$j]> $arr [$j +1]) {
$tmp = $arr [$j];
$arr [$j] = $arr [$j +1];
$arr [$j +1] = $tmp;
}}}
? >
2. Two-point insertion sequencing
Process:
1. First, the original array is an ordered sequence, $low =0 $high =count ($arr)-1.
2. Compare the number to be inserted with the element in the middle of the array.
If it is larger than the middle element, then $low= $mid +1 as the beginning of the array of the next judgment.
If it is smaller than the middle element, then $high= $mid-1 as the end of the array for the next judgment.
3. Until the end of the $low> $high, $low is where the new element is inserted.
4. Move the element from $low in the array back one bit, and then insert the new element at the $low position.
<?php
//Two-point insertion sequencing
$arr = Createarr;
$key = Mt_rand (0,99);
Printarr ($arr);
Echo ' key= '. $key. ' <br> ';
Binsort ($arr, $key);
Printarr ($arr);
function Createarr ($num =10) {
$arr = array ();
For ($i =0 $i < $num; $i + +) {
Array_push ($arr, Mt_rand (0,99));
}
Sort ($arr); Ordered sequence return
$arr;
}
function Printarr ($arr) {
echo ' arr: '. Implode (', ', $arr). ' <br> ';
}
Function Binsort (& $arr, $key) {
$low = 0;
$high = count ($arr)-1;
while ($low <= $high) {
$m = $low + (int) (($high-$low)/2);
$mkey = $arr [$m];
if ($key >= $mkey) {
$low = $m + 1;
} else{
$high = $m-1;
}
}
Moves the element after the insertion position, inserting the new element for
($i =count ($arr)-1; $i >= $low; $i-) {
$arr [$i +1] = $arr [$i];
}
$arr [$low] = $key;
}
? >