search
HomeBackend DevelopmentPHP Tutorial7 basic php sorting methods, 7 php sorting_PHP tutorial

7 basic php sorting methods, 7 php sorting

This article summarizes 7 commonly used sorting methods and implements them in php language.

1. Direct insertion sort

/*
 *  直接插入排序,插入排序的思想是:当前插入位置之前的元素有序,
 *  若插入当前位置的元素比有序元素最后一个元素大,则什么也不做,
 *  否则在有序序列中找到插入的位置,并插入
 */
function insertSort($arr) {
  $len = count($arr);  
  for($i = 1; $i < $len; $i++) {
    if($arr[$i-1] > $arr[i]) {
      for($j = $i - 1;$j >= 0; $j-- ) {
        $tmp = $arr[$j+1];
        if($tmp < $arr[$j]) {
          $arr[$j+1] = $arr[$j];
          $arr[$j] = $tmp;
        }else{
          break;
        }          
      }  
    }
  }  
  return $arr;
}

2. Bubble sort

/*
  冒泡排序,冒泡排序思想:进行 n-1 趟冒泡排序, 每趟两两比较调整最大值到数组(子数组)末尾
*/
function bubbleSort($arr) {
  $len = count($arr);
  for($i = 1; $i < $len; $i++) {
    for($j = 0; $j < $len-$i; $j++) {
      if($arr[$j] > $arr[$j+1]) {
        $tmp = $arr[$j+1];
        $arr[$j+1] = $arr[$j];
        $arr[$j] = $tmp;
      }
    }
  }
  return $arr;
}

3. Simple selection and sorting

/*
  简单选择排序, 简单排序思想:从数组第一个元素开始依次确定从小到大的元素
*/
function selectSort($arr) {
  $len = count($arr);
  for($i = 0; $i < $len; $i++) {
    $k = $i;
    for($j = $i+1; $j < $len; $j++) {
      if($arr[$k] > $arr[$j]) {
        $k = $j;
      }
    }
    if($k != $i) {
      $tmp = $arr[$i];
      $arr[$i] = $arr[$k];
      $arr[$k] = $tmp;
    }
  }
  return $arr;
}

4. Hill sorting

/*
  希尔排序,希尔排序原理:将数组按指定步长分隔成若干子序列,然后分别对子序列进行排序(在这是直接)
*/
function shellSort($arr) {
  $len = count($arr);
  $k = floor($len/2);
  while($k > 0) {
    for($i = 0; $i < $k; $i++) {
      for($j = $i; $j < $len, ($j + $k) < $len; $j = $j + $k) {
        if($arr[$j] > $arr[$j+$k]) {
          $tmp = $arr[$j+$k];
          $arr[$j+$k] = $arr[$j];
          $arr[$j] = $tmp;
        }
      }
    }
    $k = floor($k/2);
  }
  return $arr;
}

5. Quick sort

/*
 *  快速排序,快排思想:通过一趟排序将待排的记录分为两个独立的部分,其中一部分的记录的关键字均不大于
 *  另一部分记录的关键字,然后再分别对这两部分记录继续进行快速排序,以达到整个序列有序,具体做法需要
 *  每趟排序设置一个标准关键字和分别指向头一个记录的关键字和最后一个记录的关键字的指针。
 *  quickSort($arr, 0, count($arr) -1);
 */
function quickSort(&$arr,$low,$high) {
  if($low < $high) {
    $i = $low;
    $j = $high;
    $primary = $arr[$low];
    while($i < $j) {
      while($i < $j && $arr[$j] >= $primary) {
        $j--;
      }
      if($i < $j) {
        $arr[$i++] = $arr[$j];
      }
      while($i < $j && $arr[$i] <= $primary) {
        $i++;
      }
      if($i < $j) {
        $arr[$j--] = $arr[$i];
      }
    }
    $arr[$i] = $primary;
    quickSort($arr, $low, $i-1);
    quickSort($arr, $i+1, $high);
  }
}

6. Heap sort

/*
  堆排序
*/

// 调整子堆的为大根堆的过程,$s为子堆的根的位置,$m为堆最后一个元素位置
function heapAdjust(&$arr, $s, $m) {
  $tmp = $arr[$s];
  // 在调整为大根堆的过程中可能会影响左子堆或右子堆
  // for循环的作用是要保证子堆也是大根堆
  for($j = 2*$s + 1; $j <= $m; $j = 2*$j + 1) {
    // 找到根节点的左右孩子中的最大者,然后用这个最大者与根节点比较,
    // 若大则进行调整,否则符合大根堆的 特点跳出循环  
    if($j < $m && $arr[$j] < $arr[$j+1]) {
      $j++;
    }
    if($tmp >= $arr[$j] ) {
      break;
    }
    $arr[$s] = $arr[$j];
    $s = $j;
  }
  $arr[$s] = $tmp;
}

// 堆排序
function heapSort($arr) {
  $len = count($arr);
  // 依次从子堆开始调整堆为大根堆
  for($i = floor($len/2-1); $i >= 0; $i--) {
    heapAdjust($arr, $i, $len-1);
  }
  // 依次把根节点调换至最后一个位置,再次调整堆为大根堆,找到次最大值,
  // 依次类推得到一个有序数组
  for($n = $len-1; $n > 0; $n--) {
    $tmp = $arr[$n];
    $arr[$n] = $arr[0];
    $arr[0] = $tmp;
    heapAdjust($arr, 0, $n-1);
  }
  return $arr;
}

7. Merge sort

/*
  归并排序,这里实现的是两路归并
*/
// 分别将有序的$arr1[s..m]、$arr2[m+1..n]归并为有序的$arr2[s..n]
function Merge(&$arr1, &$arr2, $s, $m, $n) {
  for($k = $s,$i = $s, $j = $m+1; $i <= $m && $j <= $n; $k++) {
    if($arr1[$i]<$arr1[$j]) {
      $arr2[$k] = $arr1[$i++];
    }else {
      $arr2[$k] = $arr1[$j++];
    }
  }
  if($i <= $m) {
    for(; $i <= $m; $i++) {
      $arr2[$k++] = $arr1[$i];
    }
  } else if($j <= $n) {
    for(; $j <= $n; $j++) {
      $arr2[$k++] = $arr1[$j];
    }
  }
}

// 递归形式的两路归并
function MSort(&$arr1, &$arr2, $s, $t) {
  if($s == $t) {
    $arr2[$s] = $arr1[$s];
  }else {
    $m = floor(($s+$t)/2);
    $tmp_arr = array();
    MSort($arr1, $tmp_arr, $s, $m);
    MSort($arr1, $tmp_arr, $m+1, $t);
    Merge($tmp_arr, $arr2, $s, $m, $t);
  }
}

// 对一位数组$arr[0..n-1]中的元素进行两路归并
function mergeSort($arr) {
  $len = count($arr);
  MSort($arr, $arr, 0, $len-1);
  return $arr;
}

Usage experience
If the number n of records to be sorted is small, direct insertion sorting and simple selection sorting can be used. When the record itself has a large amount of information, it is better to use the simple selection sorting method.
If the records to be sorted are basically ordered by keyword, direct insertion sort and bubble sort are suitable.
If the value of n is large, quick sort, heap sort and merge sort can be used. In addition, quick sort is considered to be the best method among internal sorting methods.

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Articles you may be interested in:

  • Summary of PHP array sorting method recommended collection
  • PHP multi-dimensional array sorting problem based on an item in a two-dimensional array
  • Detailed explanation of PHP bubble sort binary search order search two-dimensional array sorting algorithm function
  • Detailed explanation of PHP two-dimensional array sorting
  • php two-dimensional array sorting method (array_multisort usort)
  • Sharing three ways to implement quick sorting in PHP
  • Sharing three ways to sort two-dimensional arrays in PHP and custom functions
  • PHP arrays contain Chinese sorting methods
  • Analysis on the difference between sorting functions sort, asort, rsort, krsort and ksort in PHP
  • Implementation code for sorting multi-dimensional arrays by specified value in PHP

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1110082.htmlTechArticle7 basic php sorting methods, 7 php sorting methods. This article summarizes the 7 commonly used sorting methods and uses PHP language implementation. 1. Direct insertion sort /* * Direct insertion sort, insertion sort...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.