Bubble sort
- Two or two keywords comparing adjacent records are exchanged if they are in reverse order, and large numbers sink until the maximum appears at the end of the array.
function swap(&$x, &$y) {
$temp = $x;
$x = $y;
$y = $temp;
}
function bubble_sort(&$arr) {//php arrays are treated as basic types, so the original arrays must be modified by referencing them
for ($i = 0; $i < count($arr) - 1; $i++) { //Number of control cycles
for ($j = 0; $j < count($arr) - 1 - $i; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
swap($arr[$j], $arr[$j + 1]);
}
}
}
}
Improved Bubble Sorting
- The first layer of the cycle remains unchanged, and the second layer of the cycle bubbles up from the back to the front, so that small data can be bubbled forward as much as possible in the process of bubbling.
function bubble_sort(&$arr)
{
for ($i=0;$i<count($arr);$i++) {
for ($j=count($arr)-1;$j>$i;$j--) {
if ($arr[$j-1]>$arr[j]) {
swap($arr[j-1],$arr[j]);
}
}
}
}
Insertion sort
- Insert a record into an ordered table
function insertion_sort(&$arr)
{//php arrays are treated as basic types, so the original arrays must be modified by referencing them
for ($i = 1; $i < count($arr); $i++) {
$temp = $arr[$i];
for ($j = $i - 1; $j >= 0 && $arr[$j] > $temp; $j--) {
$arr[$j + 1] = $arr[$j];
}
$arr[$j + 1] = $temp;
}
}
Selection sort
- By comparing n-i subkeywords, the smallest record i n n-i+1 record is found and exchanged with the first record.
function select_sort(&$arr)
{
for ($i = 0;$i < count($arr);$i++) {
$min = $i;
for ($j = count($arr)-1;$j > $i;$j--) {
if ($arr[$j] < $arr[$min]) {
$min = $j;
}
}
if ($min != $i) {
swap($arr[$i],$arr[$min]);
}
}
}
Why Insert Sort is Better than Bubble Sort
- The time complexity of the two algorithms is O (n^2), but each time the bubble sort exchanges records, it needs three assignment operations, while the insertion sort has sentinel variables, so it has only one assignment operation, which reduces the sorting time.
summary
- Comparing sorting algorithms are all in-place sorting algorithms with space complexity O(1). Bubble sorting and insertion sorting do not exchange equal records, so they are stable sorting. Selecting sorting is only the last exchange of minimum records, so it will destroy the relative order. Selecting sorting is not a stable algorithm.