One, sort
1, bubbling method
The core idea of the Bubbling method is 22 comparisons, which are replaced if the size is reversed. The time complexity of the Bubbling method is O (n*n)
function Maopao_sort ($arr) {
$len = count ($arr);
for ($i =0; $i < $len; $i + +) {
for ($j =0; $j < $len-$i-1; $j + +) {
if ($arr [$j]> $arr [$j +1]) {
$temp = $arr [$j];
$arr [$j] = $arr [$j +1];
$arr [$j +1] = $temp;
}
}
}
return $arr;
}
2, fast sorting method
The idea of the fast sorting method is to divide the number of orders to be sorted into two groups, the left side is smaller than the right, and then recursively, the average run time of the fast sort is θ (NLOGN)
function Quick_sort ($arr) {
$len = count ($arr);
if ($len <=1) {
return $arr;
}else{
$key = $arr [0];
$left = Array ();
$right = Array ();
for ($i =1; $i < $len; $i + +) {
if ($key >= $arr [$i]) {
$left []= $arr [$i];
}else{
$right []= $arr [$i];
}
}
$left = Quick_sort ($left);
$right = Quick_sort ($right);
Return Array_merge ($left, Array ($key), $right);
}
}
3, select the sorting method
Simple selection of the basic idea of sorting: The 1th trip, in order to sort records R[1]~r[n] to select the smallest record, it and R[1] Exchange, 2nd trip, in order to sort records R[2]~r[n] to select the smallest record, and r[2] exchange; And so on, the first trip to sort records r[i]~r[n ], the smallest record is selected, and it is exchanged with r[i], so that the ordered sequence continues to grow until all sorts are completed.
function Select_sort ($arr) {
$len = count ($arr);
for ($i =0; $i < $len; $i + +) {
for ($j = $i +1; $j < $len; $j + +) {
if ($arr [$i]> $arr [$j]) {
$temp = $arr [$i];
$arr [$i] = $arr [$j];
$arr [$j] = $temp;
}
}
}
return $arr;
}
4, insert Sort method
The core idea of the insertion sorting method is to assume that the first number is already in sequence, starting with the second number, from the back-to-front sweep of the finished sequence, to find the right position, to insert. All subsequent numbers move back.
function Insert_sort ($arr) {
$len = count ($arr);
for ($i =1; $i < $len; $i + +) {
$temp = $arr [$i];
$j = $i-1;
while ($j >=0 && $arr [$j]> $temp) {
$arr [$j +1]= $arr [$j];
$arr [$j] = $temp;
$j--;
}
}
return $arr;
}
PHP several algorithms