Home > Backend Development > PHP Tutorial > PHP quick sort code

PHP quick sort code

不言
Release: 2023-04-02 16:32:01
Original
1714 people have browsed it

This article mainly introduces the code for quick sorting in PHP, which has a certain reference value. Now I share it with you. Friends in need can refer to it

1. Introduction to the principle

Actually, it’s very simple
An array[6, 1, 2, 7, 9, 3, 4, 5, 10, 8]
a. Find the first 6 (any Both will work)
b. Separate the ones smaller than 6 and those larger than 6, each into an array
c. Obtain two arrays through b operation, then repeat the ab operation, and finally merge the arrays

2. Code

/**
 * 快速排序
 */
function quick_sort($arr)
{
    $length = count($arr);
    if ($length <= 1) {
        return $arr;
    }
    $left = $right = [];
    for ($i = 1; $i < $length; $i++) {
        if ($arr[$i] < $arr[0]) {
            $left[] = $arr[$i];
        } else {
            $right[] = $arr[$i];
        }

    }
    //递归调用
    $left = quick_sort($left);
    $right = quick_sort($right);
    return array_merge($left, [$arr[0]], $right);
}
$arr_data = [6, 1, 2, 7, 9, 3, 4, 5, 10, 8];
print_r(quick_sort($arr_data));
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Keywords such as scope, global, static, etc. of PHP variables

Commonly used headers in PHP Header definition

The above is the detailed content of PHP quick sort code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template