Detailed explanation of four basic PHP algorithms

Many people say that algorithm is the core of a program and that a program is better than a program,The key is the quality of this program algorithm. As a beginner phper,Although there is little contact with algorithms. But for bubble sorting, insert sorting, select sorting, fast sorting four basic algorithms, I want to master.

Requirements: Use bubble sort, quick sort, select sort, insert sort, merge sort to sort the values in the following array from smallest to largest.

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

1. Bubble sort

Introduction:

Bubble Sort is a simple sorting algorithm. It repeatedly visits the columns to be sorted, compares two elements in turn, and swaps them over if they are in the wrong order. The work of visiting a number of columns is repeated until no exchanges are needed, that is, the columns have been sorted. The name of this algorithm comes from the fact that smaller elements "float" slowly to the top of a number of columns through an exchange.

Steps:

  1. Compare adjacent elements. If the first one is bigger than the second, swap the two.
  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 maximum number.
  3. Repeat the above steps for all elements except the last one.
  4. Continue repeating the above steps for fewer and fewer elements each time until no pair of numbers need to be compared.

Code:

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39, 2];
//Bubble sort
function bubbleSort($arr) {
$len = count($arr);
//This layer of cycle control requires the number of wheels to bubble
for ($i = 1; $i < $len; $i++) {
//This layer loop is used to control the number of times a number of comparisons occur in each round
for ($k = 0; $k < $len - $i; $k++) {
if ($arr[$k] > $arr[$k + 1]) { //From Small to Large < || From Large to Small >
$tmp = $arr[$k + 1]; // Declare a temporary variable
$arr[$k + 1] = $arr[$k];
$arr[$k] = $tmp;
}
}
}
return $arr;
}

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

Sorting effect:

 

2. Select Sort

Introduction:

Selection sort is a simple and intuitive sorting algorithm. It works as follows. First the smallest element is found in the unsorted sequence and stored at the beginning of the sequence. Then the smallest element is found from the remaining unsorted elements and placed at the end of the sequence. And so on until all the elements are sorted.

Code:

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39, 2];
//Select Sort
//The dual loop of ideas is completed, the number of outer control wheels, the current minimum. Number of internal control comparisons
function selectSort($arr) {

    $len = count($arr);

    //$i The position of the current minimum, which requires elements to participate in the comparison
    for ($i = 0; $i < $len - 1; $i++) {
        //Assume the location of the minimum value first
        $p = $i;

        //Which elements do $j currently need to be compared to, $i behind.
        for ($j = $i + 1; $j < $len; $j++) {
            //$arr[$p] is the minimum currently known
            //Compare, find smaller, record the location of the minimum value; And the next comparison should use the known minimum.
            $p = ($arr[$p] <= $arr[$j]) ? $p : $j;
        }

        //The location of the current minimum has been determined and saved to $p.
        //If you find that the location of the minimum value is different from the current hypothetical location of $i, you can swap the locations
        if ($p != $i) {
            $tmp     = $arr[$p];
            $arr[$p] = $arr[$i];
            $arr[$i] = $tmp;
        }
    }
    //Return the final result
    return $arr;
}

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

 

3. Insert Sort

Introduction:

The algorithm description of Insertion Sort is a simple and intuitive sorting algorithm. It works by building an ordered sequence, and for unsorted data, scanning backwards and forwards in the ordered sequence to find the corresponding location and insert it. Insertion sorting is implemented by in-place sorting (that is, sorting using only the extra space of O(1). As a result, the sorted elements need to be moved backwards repeatedly to provide insertion space for the latest elements in the back-to-front scan process.

Steps:

  1. Starting with the first element, the element can be thought to have been sorted
  2. Remove the next element and scan backwards and forwards in the sorted element sequence
  3. If the element (sorted) is larger than the new element, move the element to the next location
  4. Repeat step 3 until you find a position where the sorted element is less than or equal to the new element
  5. Insert a new element into this location
  6. Repeat Step 2

Code:

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39,2];
//Insert Sort
function insert_sort($arr)
{
$len=count($arr);
for($i=1; $i<$len; $i++) {
//Get the value of the element currently being compared
$tmp = $arr[$i];
//Inner loop control comparison and insertion
for($j=$i-1; $j>=0; $j--) {
//$arr[$i]; Elements to be inserted
//$arr[$j]; Elements to compare
if($tmp < $arr[$j]) //From Small to Large < || From Large to Small >
{
//Found insert element small, swap position
//Swap back elements with front elements
$arr[$j+1] = $arr[$j];

//Set the previous number to the current number you want to swap
$arr[$j] = $tmp;
} else {
//If you encounter elements that do not need to be moved
//Since the arrays are already sorted, the previous ones do not need to be compared again.
break;
}
}
}
//Insert this element into the sorted sequence.
//Return
return $arr;
}

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

Sorting effect:

 

 

 

 

 

 

 

4. Quick Sort

Introduction:

Quick sorting is a sort algorithm developed by Tony Hall. On average, sort n items to Ο (n log n) comparisons. In the worst case you need Ο (n2) comparisons, but this is not common. In fact, quick sorting is often significantly more common than other Ο The (n log n) algorithm is faster because its inner loop can be efficiently implemented on most architectures, and in most real-world data, it determines the design choice and reduces the likelihood of a quadratic term that takes time.

Steps:

  1. Pick out an element from the column called a pivot.
  2. Reorder the number columns, all elements smaller than the base value are placed in front of the base, and all elements larger than the base value are placed behind the base (the same number can be on either side). After the partition exits, the benchmark is in the middle of the column. This is called a partition operation.
  3. Recursively sorts subordinate columns of elements smaller than the base value and those larger than the base value.

Code:

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39,2];
//Quick Sort
function quick_sort($arr)
{
//Determine if a parameter is an array
if(!is_array($arr)) return false;

//Recursive Exit: Array length is 1, return array directly
$length = count($arr);

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

//If there are more than one array element, two empty arrays are defined
$left = $right = array();

//Traverse using a for loop, using the first element as the object of comparison
for($i=1; $i<$length; $i++)
{
//Determine the size of the current element
if($arr[$i] < $arr[0]){ //From Small to Large < || From Large to Small >
$left[]=$arr[$i];
}else{
$right[]=$arr[$i];
}
}

//Recursive call
$left=quick_sort($left);
$right=quick_sort($right);

//Merge all results
return array_merge($left,array($arr[0]),$right);
}

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

Sorting effect:

4. Merge Sort

Use recursion to split, merge, and sort.

Steps:

  • The mean score is listed as two subordinate columns
  • Repeat the last step recursively until the child column has only one element
  • Parent column merges two child columns and sorts them, returning them recursively

Code:

<?php
$arr = [1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39,2];

// Merge Sort Main
function mergeSort($arr) {
$len = count($arr);

// Recursive end condition, at this point, the array is left with only one element, that is, the array is separated
if ($len <= 1) {
return $arr;
}

$mid = intval($len / 2); // Take the middle of the array
$left = array_slice($arr, 0, $mid); // Split the 0-mid part of the group to the left
$right= array_slice($arr, $mid); // Split the mid-end part of the group to the right
$left = mergeSort($left); // Recursive merge up after left split
$right= mergeSort($right); // Right split begins to recursively move up
$arr = merge($left, $right); // Merge two arrays and continue recursion

return $arr;
}

// The merge function combines and sorts two specified ordered arrays (arrA, arr)
function merge($arrA, $arrB) {
$arrC = array();
while (count($arrA) && count($arrB)) {
// If you keep trying to decide which value is small, you will give the small value to arrC, but in the end there must be a few remaining values.
// Either inside the remaining arrA or inside the remaining arrB, and these ordered values must be larger than all the values in the arrC, so use
//From Small to Large < || From Large to Small >
$arrC[] = $arrA[0] < $arrB[0] ? array_shift($arrA) : array_shift($arrB);
}

return array_merge($arrC, $arrA, $arrB);
}

$arr = mergeSort($arr);
print_r($arr);

Sorting effect:

 

 

Posted on Thu, 04 Nov 2021 17:06:43 -0400 by bigphpn00b