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

PHP quick sort code

不言
不言Original
2018-07-06 11:00:241708browse

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));

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!

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