Home Backend Development PHP Tutorial How to implement quick sort non-recursive algorithm in PHP

How to implement quick sort non-recursive algorithm in PHP

Apr 05, 2023 pm 02:38 PM

Introduction

Quick sort is an efficient sorting algorithm that implements sorting by continuously dividing an array into two sub-arrays. In the quick sort algorithm, a pivot value is selected and all elements smaller than the pivot value are placed on its left side, while all elements greater than the pivot value are placed on its right side. This process is then applied recursively to the left and right subarrays until the entire array is sorted.

Quick sort is a recursive function because it needs to decompose the original problem into two smaller sub-problems, and then solve the original problem by solving these sub-problems recursively. While this approach can work effectively in some situations, it has some limitations. Specifically, when processing large arrays, recursive algorithms may exhaust the computer's stack space, causing a stack overflow exception. In addition, the additional overhead of recursive function calls may also cause performance degradation of the algorithm.

Therefore, in some cases, it may be more appropriate to use non-recursive implementation methods. In this article, we will introduce a non-recursive algorithm for quick sort using PHP.

Algorithm implementation

We first define an auxiliary function partition, which is used to divide an array into two sub-arrays: one containing all elements smaller than the baseline value, and one containing all elements greater than the baseline value.

function partition(&$arr, $left, $right) {
    $pivot = $arr[$right]; // 选择最后一个元素作为基准值
    $i = $left - 1;
    for ($j = $left; $j < $right; $j++) {
        if ($arr[$j] < $pivot) {
            $i++;
            list($arr[$i], $arr[$j]) = array($arr[$j], $arr[$i]); // 交换i和j处的元素
        }
    }
    list($arr[$i + 1], $arr[$right]) = array($arr[$right], $arr[$i + 1]); // 将基准值放到正确的位置
    return $i + 1;
}
Copy after login

This function selects the last element from the array as the pivot value and puts all elements smaller than the pivot value to the left side of the array by swapping the array elements. In this process, we use the variable $i to record the subscript of the currently processed subarray, and $j is used to traverse the entire array. When we find an element that is smaller than the pivot value, we move $i one position to the right and place the element at $i's position. Finally, we place the base value at the final position $i 1 .

With the partition function, we can now implement a non-recursive version of the quicksort algorithm. In this version, we use a stack to store the subarrays to be processed. When we process a subarray, we first record the left and right boundaries of the subarray on the stack, and then continue to divide it into two smaller subarrays until all subarrays are sorted.

function quick_sort(&$arr) {
    $stack = new SplStack(); // 使用SplStack实现栈
    $stack->push(count($arr) - 1); // 将整个数组的下标压入栈
    $stack->push(0);
    while (!$stack->isEmpty()) {
        $left = $stack->pop();
        $right = $stack->pop();
        $pivotIndex = partition($arr, $left, $right);
        if ($left < $pivotIndex - 1) {
            $stack->push($pivotIndex - 1);
            $stack->push($left);
        }
        if ($pivotIndex + 1 < $right) {
            $stack->push($right);
            $stack->push($pivotIndex + 1);
        }
    }
}
Copy after login

In this version of the code, we use the SplStack class to implement the stack. We first push the left and right boundaries of the entire array onto the stack, then continuously remove the left and right boundaries from the stack and pass them to the partition function to divide the subarray. If left < pivotIndex - 1, it means that the left subarray is not yet sorted and is pushed onto the stack to wait for processing. Similarly, if pivotIndex 1 < right, it means that the right subarray is not yet sorted and is pushed onto the stack for processing.

The time complexity of this algorithm is O(nlogn). Although it is not as fast as the recursive version of quicksort in all cases, it can significantly reduce the space complexity of the algorithm and avoid the overhead of recursive function calls. If you need to quickly sort a large array in PHP, this algorithm may suit your needs better than the recursive version of quicksort.

The above is the detailed content of How to implement quick sort non-recursive algorithm in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

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 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...

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 late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

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.

See all articles