Home  >  Article  >  Backend Development  >  PHP implements several common sorting algorithms

PHP implements several common sorting algorithms

小云云
小云云Original
2018-03-10 13:34:426977browse

Exchange sorting: The basic idea of ​​exchange sorting is to compare the sizes of the key values ​​​​of the two records. If the sizes of the key values ​​​​of the two records appear in reverse order, exchange the two records, so that the record with the smaller key value is moved to Move to the front of the sequence, and records with larger key values ​​move to the back of the sequence.




# 1. Bubble sort

Introduction:

Bubble Sort (Bubble Sort, Taiwanese translation: Bubble Sorting or bubble sort) is a simple sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through swapping.

Steps:

  1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.

  2. Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. 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 repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

##Bubble sort is the simplest to understand, but the time complexity is ( O(n^2)) is also one of the largest. The implementation code is as follows:

<br/>
  1. $arr=array(1,43,54,62,21,66 ,32,78,36,76,39);

  2. ##function getpao($arr)

  3. ##{

  4. ##$len

    =count($arr);

  5. //Set an empty array to receive bubbles that pop up

  6. //This layer loop controls the number of rounds that need to bubble

  7. for

    ($i=1;$i8a8c0d31fd7be7c47a3e6eaa6b38e8de$arr[$k+1])  

  •         {  

  •             $tmp=$arr[$k+1];  

  •             $arr[$k+1]=$arr[$k];  

  •              $arr[$k]=$tmp;

  • ##                                                 

  • # }
  • ##return
  • $ arr

  • ;
  • }

  • 2. Quick sort
  • Introduction:

    Quick sort was developed by Tony HallA sorting algorithm developed. Under average circumstances, sorting n items requires

    Ο

    (n log

    n

    ) comparisons. In the worst case, Ο(n2) comparisons are required, but this situation is uncommon. In fact, quicksort is often significantly faster than other Ο(n log n) algorithms because its inner loop can be used in most The architecture is implemented very efficiently, and in most real-world data, it is possible to determine the design choices and reduce the time required by the quadratic term. step:

    1. Pick out an element from the sequence, called the "pivot",

    2. Reorder the sequence , 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 go to either side). After this partition exits, the base is in the middle of the sequence. This is called a partition operation.

    3. Recursively sort the subarray of elements smaller than the base value and the subarray of elements greater than the base value.

    Quick sort is also an efficient sorting algorithm, and its time complexity is also O( nlogn). The code is as follows:

    1. ##function

      quick_sort($arr) {

    2. //First determine whether you need to continue

    3. $length

      = count($arr);

    4. ##if
    5. ($length 5fabf8a01ba2ef742ab2307b6afcc6ec $arr[$j]) { //Compare, find the smaller one, record the position of the minimum value; and in the next comparison,

    6. // The known minimum value should be used for comparison.

    7. ##                                  $p

      =
    8. $j

      ;

    9.           //The current minimum value position has been determined and saved to $p.

    10. //If it is found that the position of the minimum value is different from the current assumed position $i, then the positions are mutually exclusive Just change it

    11. ##if($p != $i) {

    12. ##                                  

      ## = $arr[$p];

                    
    13. $arr
    14. [$p] = $arr [$i]; ##         

      $arr
    15. [

      $i] = $tmp; } }

    16. }

    17. //Return the final result

    18. ## return $arr;

    19. }

    4. Heap sort

    Introduction:

    Stacking sort (Heapsort) refers to a sorting algorithm designed using the data structure of heap. The heap is a structure that approximates a complete binary tree, and simultaneously satisfies the heap properties: that is, the A key or index is always smaller (or larger) than its parent node.

    Steps:

    Heap sorting refers to a sorting algorithm designed using the data structure of a stacked tree (heap) , using the characteristics of arrays to quickly locate the element at the specified index. The heap is divided into a large root heap and a small root heap, which is a complete binary tree. The requirement of a large root heap is that the value of each node is not greater than the value of its parent node, that is, A[PARENT[i]] >= A[i]. In non-descending sorting of an array, a large root heap needs to be used, because according to the requirements of a large root heap, the largest value must be at the top of the heap.

    Sort effect:


    堆排序是一种高效的排序算法,它的时间复杂度是O(nlogn)。原理是:先把数组转为一个最大堆,然后把第一个元素跟第i元素交换,然后把剩下的i-1个元素转为最大堆,然后再把第一个元素与第i-1个元素交换,以此类推。实现代码如下:

    function heapSort($arr) {
        $len = count($arr);    // 先建立最大堆
        for ($i = floor(($len - 1) / 2); $i >= 0; $i--) {        $s = $i;        $childIndex = $s * 2 + 1;        while ($childIndex < $len) {            // 在父、左子、右子中 ,找到最大的
                if ($childIndex + 1 < $len && $arr[$childIndex] < $arr[$childIndex + 1]) $childIndex++;            if ($arr[$s] < $arr[$childIndex]) {                $t = $arr[$s];                $arr[$s] = $arr[$childIndex];                $arr[$childIndex] = $t;                $s = $childIndex;                $childIndex = $childIndex * 2 + 1;
                } else {                break;
                }
            }
        }    // 从最后一个元素开始调整
        for ($i = $len - 1; $i > 0; $i--) {        $t = $arr[$i];        $arr[$i] = $arr[0];        $arr[0] = $t;        // 调整第一个元素
            $s = 0;        $childIndex = 1;        while ($childIndex < $i) {            // 在父、左子、右子中 ,找到最大的
                if ($childIndex + 1 < $i && $arr[$childIndex] < $arr[$childIndex + 1]) $childIndex++;            if ($arr[$s] < $arr[$childIndex]) {                $t = $arr[$s];                $arr[$s] = $arr[$childIndex];                $arr[$childIndex] = $t;                $s = $childIndex;                $childIndex = $childIndex * 2 + 1;
                } else {                break;
                }
            }
        }    return $arr;
    }$arr = [3,1,13,5,7,11,2,4,14,9,15,6,12,10,8];
    print_r(bubbleSort($arr));


    插入排序 

    五、插入排序 

    介绍:

    插入排序(Insertion Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

    步骤:

    1. 从第一个元素开始,该元素可以认为已经被排序

    2. 取出下一个元素,在已经排序的元素序列中从后向前扫描

    3. 如果该元素(已排序)大于新元素,将该元素移到下一位置

    4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置

    5. 将新元素插入到该位置中

    6. 重复步骤2


    感觉插入排序跟冒泡排序有点相似,时间复杂度也是O(n^2),实现代码如下:


    [php] view plain copy


    1. ##function insert_sort($arr) {

    2. //Distinguish which part has been sorted

    3. ##/ /Which part is not sorted

    4. ##//Find one of the elements that needs to be sorted

    5. ##//This element starts from the second element and ends with the last element that needs to be sorted
    6. //You can mark it by using a loop
    7. //i loop controls the elements that need to be inserted each time. Once the elements that need to be inserted are controlled,
    8. //Indirectly the array has been divided into 2 parts, the subscript is smaller than the current one (left one), it is the sorted sequence
    9. for($i=1, $len=count($arr); $i< ;$len; $i++) {

    10. ##         //Get the current element value that needs to be compared.

    11. $tmp = $arr [$i];

    12. #         

      //Inner loop control Compare and insert

    13. ##for

      ($j=$i-1;$j>=0;$j --) {

    14. //$arr[$i];//Elements that need to be inserted; $arr[$j];//Elements that need to be compared

    15. ##                  if($tmp 03e4d377d46ad1a6733bed31aeaeeb6b

      排序效果:


      希尔排序其实可以理解是插入排序的一个优化版,它的效率跟增量有关,增量要取多少,根据不同的数组是不同的,所以希尔排序是一个不稳定的排序算法,它的时间复杂度为O(nlogn)到O(n^2)之间,实现代码如下:

      function shellSort($arr) {
          $len = count($arr);    $stepSize = floor($len / 2);    while ($stepSize >= 1) {        for ($i = $stepSize; $i < $len; $i++) {            if ($arr[$i] < $arr[$i - $stepSize]) {                $t = $arr[$i];                $j = $i - $stepSize;                while ($j >= 0 && $t < $arr[$j]) {                    $arr[$j + $stepSize] = $arr[$j];                    $j -= $stepSize;
                      }                $arr[$j + $stepSize] = $t;
                  }
              }        // 缩小步长,再进行插入排序
              $stepSize = floor($stepSize / 2);
          }    return $arr;
      }$arr = [3,1,13,5,7,11,2,4,14,9,15,6,12,10,8];
      print_r(bubbleSort($arr));


      七、归并排序 

      介绍:

      归并排序(Merge sort,台湾译作:合并排序)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(pide and Conquer)的一个非常典型的应用

      步骤:

      1. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列

      2. 设定两个指针,最初位置分别为两个已经排序序列的起始位置

      3. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置

      4. 重复步骤3直到某一指针达到序列尾

      5. 将另一序列剩下的所有元素直接复制到合并序列尾

      排序效果:


      归并排序的时间复杂度也是O(nlogn)。原理是:对于两个排序好的数组,分别遍历这两个数组,获取较小的元素插入新的数组中,那么,这么新的数组也会是排序好的。代码如下:

      我们先来看看主函数部分:

      //交换函数function swap(array &$arr,$a,$b){
          $temp = $arr[$a];    $arr[$a] = $arr[$b];    $arr[$b] = $temp;
      }//归并算法总函数function MergeSort(array &$arr){
          $start = 0;    $end = count($arr) - 1;
          MSort($arr,$start,$end);
      }

      在总函数中,我们只调用了一个 MSort() 函数,因为我们要使用递归调用,所以将 MSort() 封装起来。

      下面我们来看看 MSort() 函数:

      function MSort(array &$arr,$start,$end){    //当子序列长度为1时,$start == $end,不用再分组    if($start < $end){        $mid = floor(($start + $end) / 2);	//将 $arr 平分为 $arr[$start - $mid] 和 $arr[$mid+1 - $end]        MSort($arr,$start,$mid);			//将 $arr[$start - $mid] 归并为有序的$arr[$start - $mid]        MSort($arr,$mid + 1,$end);			//将 $arr[$mid+1 - $end] 归并为有序的 $arr[$mid+1 - $end]        Merge($arr,$start,$mid,$end);       //将$arr[$start - $mid]部分和$arr[$mid+1 - $end]部分合并起来成为有序的$arr[$start - $end]
          }
      }

      上面的 MSort() 函数实现将数组分半再分半(直到子序列长度为1),然后将子序列合并起来。

      现在是我们的归并操作函数 Merge() :

      //归并操作function Merge(array &$arr,$start,$mid,$end){
          $i = $start;    $j=$mid + 1;    $k = $start;    $temparr = array();    while($i!=$mid+1 && $j!=$end+1)
          {       if($arr[$i] >= $arr[$j]){           $temparr[$k++] = $arr[$j++];
             }       else{           $temparr[$k++] = $arr[$i++];
             }
          }    //将第一个子序列的剩余部分添加到已经排好序的 $temparr 数组中
          while($i != $mid+1){        $temparr[$k++] = $arr[$i++];
          }    //将第二个子序列的剩余部分添加到已经排好序的 $temparr 数组中
          while($j != $end+1){        $temparr[$k++] = $arr[$j++];
          }    for($i=$start; $i<=$end; $i++){        $arr[$i] = $temparr[$i];
          }
      }

      到了这里,我们的归并算法就完了。我们调用试试:

      $arr = array(9,1,5,8,3,7,4,6,2);
      MergeSort($arr);
      var_dump($arr);

      相关推荐:

      php冒泡、选择、插入和快速排序算法分享

      PHP多维数组排序算法分析

      PHP排序算法系列之直接选择排序详解

    The above is the detailed content of PHP implements several common sorting algorithms. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn