PHP uses four basic algorithms

Many people say that an algorithm is the core of a program, and that a program is better than bad, and the key is the pros and cons of the program's algorithm. As a junior phper, although he rarely comes into contact with algorithms. But for the four basic algorithms of bubble sorting, insertion sorting, selection sorting, and quick sorting, I think I still have to master them.

需求:分别用 冒泡排序法,快速排序法,选择排序法,插入排序法,归并排序将下面数组中 的值按照从小到大的顺序进行排序。

$arr=array(11,3,56,62,21,66,32,78,36,76,39,88,34);

1. Bubble sorting
Introduction:

Bubble Sort is a simple sorting algorithm. It repeatedly visited the sequence to be sorted, compared two elements in turn, and exchanged them if they were in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, that is to say, the sequence has been sorted. The origin of the name of this algorithm is because the smaller the element will slowly "float" to the top of the sequence through exchange.

step:

1. Compare adjacent elements. If the first one is larger than the second one, swap the two of them.
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements except the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39, 2];
//冒泡排序
function bubbleSort($arr) {
    
    
    $len = count($arr);
    //该层循环控制 需要冒泡的轮数
    for ($i = 1; $i < $len; $i++) {
    
    
        //该层循环用来控制每轮 冒出一个数 需要比较的次数
        for ($k = 0; $k < $len - $i; $k++) {
    
    
            if ($arr[$k] > $arr[$k + 1]) {
    
        //从小到大 < || 从大到小 >
                $tmp         = $arr[$k + 1]; // 声明一个临时变量
                $arr[$k + 1] = $arr[$k];
                $arr[$k]     = $tmp;
            }
        }
    }
    return $arr;
}

$arr = bubbleSort($arr);
print_r($arr);

Sorting effect:
Insert picture description here
2. Select sorting
Introduction:

Selection sort is a simple and intuitive sorting algorithm. It works as follows. First find the smallest element in the unsorted sequence, store it at the beginning of the sorted sequence, and then continue to find the smallest element from the remaining unsorted elements, and then put it at the end of the sorted sequence. And so on, until all elements are sorted.

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39, 2];
//选择排序
//实现思路 双重循环完成,外层控制轮数,当前的最小值。内层控制比较次数
function selectSort($arr) {
    
    

    $len = count($arr);

    //$i 当前最小值的位置, 需要参与比较的元素
    for ($i = 0; $i < $len - 1; $i++) {
    
    
        //先假设最小的值的位置
        $p = $i;

        //$j 当前都需要和哪些元素比较,$i 后边的。
        for ($j = $i + 1; $j < $len; $j++) {
    
    
            //$arr[$p] 是 当前已知的最小值
            //比较,发现更小的,记录下最小值的位置;并且在下次比较时,应该采用已知的最小值进行比较。
            $p = ($arr[$p] <= $arr[$j]) ? $p : $j;
        }

        //已经确定了当前的最小值的位置,保存到$p中。
        //如果发现 最小值的位置与当前假设的位置$i不同,则位置互换即可
        if ($p != $i) {
    
    
            $tmp     = $arr[$p];
            $arr[$p] = $arr[$i];
            $arr[$i] = $tmp;
        }
    }
    //返回最终结果
    return $arr;
}

$arr = selectSort($arr);
print_r($arr);

Insert picture description here
3. Insertion sort
Introduction:

The algorithm description of Insertion Sort is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence. For unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert it. Insertion sorting is usually implemented by in-place sorting (that is, sorting that only uses O(1) extra space). Therefore, in the process of scanning from back to forward, it is necessary to repeatedly shift the sorted elements backwards step by step. , To provide insertion space for the latest elements.

step:

1. Starting from the first element, the element can be considered to have been sorted
2. Take out the next element and scan from back to forward in the sorted sequence of elements
3. If the element (sorted) is greater than the new element, it Move the element to the next position
4. Repeat step 3 until you find the position where the sorted element is less than or equal to the new element
5. Insert the new element into the position
6. Repeat step 2

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39,2];
//插入排序
function insert_sort($arr)
{
    
    
    $len=count($arr);
    for($i=1; $i<$len; $i++) {
    
    
        //获得当前需要比较的元素值
        $tmp = $arr[$i];
        //内层循环控制 比较 并 插入
        for($j=$i-1; $j>=0; $j--) {
    
    
            //$arr[$i];需要插入的元素
            //$arr[$j];需要比较的元素
            if($tmp < $arr[$j])   //从小到大 < || 从大到小 >
            {
    
    
                //发现插入的元素要小,交换位置
                //将后边的元素与前面的元素互换
                $arr[$j+1] = $arr[$j];

                //将前面的数设置为 当前需要交换的数
                $arr[$j] = $tmp;
            } else {
    
    
                //如果碰到不需要移动的元素
                //由于是已经排序好是数组,则前面的就不需要再次比较了。
                break;
            }
        }
    }
    //将这个元素 插入到已经排序好的序列内。
    //返回
    return $arr;
}

$arr = insert_sort($arr);
print_r($arr);

Insert picture description here
4. Quick Sort
Introduction:

Quick sort is a sorting algorithm developed by Tony Hall. On average, it takes Ο (n log n) comparisons to sort n items. In the worst case, Ο(n2) comparisons are required, but this situation is not common. In fact, quicksort is usually significantly faster than other Ο(n log n) algorithms, because its inner loop can be implemented efficiently in most architectures, and in most real-world applications. Data can determine the choice of design and reduce the possibility of quadratic terms of time required.

step:

1. Pick out an element from the number sequence and call it a "pivot".
2. Reorder the sequence so that all elements smaller than the reference value are placed in front of the reference, and all elements larger than the reference value are placed behind the reference. (The same number can go to either side). After the partition exits, the benchmark is in the middle of the sequence. This is called a partition operation.
3. Recursively sort the sub-sequences of elements smaller than the reference value and the sub-sequences of elements greater than the reference value.

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39,2];
//快速排序
function quick_sort($arr)
{
    
    
    //判断参数是否是一个数组
    if(!is_array($arr)) return false;

    //递归出口:数组长度为1,直接返回数组
    $length = count($arr);

    if($length<=1) return $arr;

    //数组元素有多个,则定义两个空数组
    $left = $right = array();

    //使用for循环进行遍历,把第一个元素当做比较的对象
    for($i=1; $i<$length; $i++)
    {
    
    
        //判断当前元素的大小
        if($arr[$i] < $arr[0]){
    
      //从小到大 < || 从大到小 >
            $left[]=$arr[$i];
        }else{
    
    
            $right[]=$arr[$i];
        }
    }

    //递归调用
    $left=quick_sort($left);
    $right=quick_sort($right);

    //将所有的结果合并
    return array_merge($left,array($arr[0]),$right);
}

$arr = quick_sort($arr);
print_r($arr);

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45557228/article/details/112660155