Table of Contents
Articles you may be interested in:
Home Backend Development PHP Tutorial Three methods of quick sorting in php

Three methods of quick sorting in php

Jul 25, 2016 am 08:53 AM

  1. function quick_sort($array) {
  2. if(count($array) <= 1) return $array;
  3. $key = $array[0];
  4. $rightArray = array( );
  5. $leftArray = array();
  6. for($i = 1; $i < count($array); $i++) {
  7. if($array[$i] >= $key) {
  8. $ rightArray[] = $array[$i];
  9. } else {
  10. $leftArray[] = $array[$i];
  11. }
  12. }
  13. $leftArray = quick_sort($leftArray);
  14. $rightArray = quick_sort($rightArray );
  15. return array_merge($leftArray, array($key), $rightArray);
  16. }
Copy code

Method 2: This algorithm comes from the Introduction to Algorithms and is called the Nico Lomuto method (details are available on goole if you are interested Description) Find the median value using the most classic one-way traversal. But this algorithm is O(n*n) in the worst case (for example, an array with the same value requires n-1 divisions, and each division requires O(n) time to remove an element). Code:

  1. function quick_sort(&$array, $start, $end) {
  2. if ($start >= $end) return;
  3. $mid = $start;
  4. for ($i = $start + 1; $i <= $end; $i++) {
  5. if ($array[$i] < $array[$mid]) {
  6. $mid++;
  7. $tmp = $array[$i ];
  8. $array[$i] = $array[$mid];
  9. $array[$mid] = $tmp;
  10. }
  11. }
  12. $tmp = $array[$start];
  13. $array[$start] = $array[$mid];
  14. $array[$mid] = $tmp;
  15. quick_sort($array, $start, $mid - 1);
  16. quick_sort($array, $mid + 1, $end);
  17. }
Copy code

Method 3: This method is basically a common textbook writing method. First, traverse from left to right to skip elements smaller than the middle element, and at the same time, traverse from right to left to skip large elements. ,Then If there is no cross-exchange of values ​​on both sides, continue looping until the middle point is found. Note that this method still swaps when processing the same elements, so there is O(nlogn) in the worst case efficiency. But in the following function, if $array[$right] > $key is changed to $array[$right] >=$key ​​or $array[$left] < $key is changed to $array[$left] <= $key is the worst Not only will the situation degrade to O(n*n), but in addition to the consumption of each comparison, there will also be the additional overhead of n interactions. There are two other test points for this question, for students who memorize by rote: 1. Are the two whiles in the middle interchangeable? Of course, it cannot be interchanged, because fast disk requires an extra space to save the initial left value. In this way, when the left and right are interchanged, the right side is used to overwrite the saved value first. is the lvalue of the median, otherwise problems will occur. See this sentence $array[$left] = $array[$right]; 2. $array[$right] = $key; The meaning of this statement can be omitted. This sentence cannot be omitted. You can consider an extreme case such as the ordering of two values ​​​​(5,2), and you will understand it step by step. Code: < $key改成$array[$left] <= $key则最坏 情况不但会堕落为O(n*n).而且除了每次比较的消耗外,还会产生n次交互的额外开销。该题还有另外两个考点,针对死记硬背的同学: 1,中间的两个while可否互换。当然不能互换,因为对于快盘需要一个额外的空间保存初始的左值,这样左右互换的时候,先用右边覆盖已经保存 为中值的左值,否则会出现问题。见这句$array[$left] = $array[$right]; 2,$array[$right] = $key; 该语句含义可否省略。该句不能省略,大家可以考虑一个极端情况比如两个值的排序(5,2),逐步看下就明白了。 代码:

  1. function quick_sort_swap(&$array, $start, $end) {
  2. if($end <= $start) return;
  3. $key = $array[$start];
  4. $left = $start;
  5. $right = $end;
  6. while($left < $right) {
  7. while($left < $right && $array[$right] > $key)
  8. $right-- ;
  9. $array[$left] = $array[$right];
  10. while($left < $right && $array[$left] < $key)
  11. $left++;
  12. $array[$right] = $ array[$left];
  13. }
  14. $array[$right] = $key;
  15. quick_sort_swap(&$array, $start, $right - 1);
  16. quick_sort_swap(&$array, $right+1, $end) ;
  17. }
Copy code

Articles you may be interested in:

  • PHP practical quick sorting algorithm example code
  • Sharing examples of php associative array sorting and quick sorting
  • php function to implement quick sort
  • php function to implement quick sort
  • Examples of php bubble sort and quick sort


Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

See all articles