PHP four basic algorithm----fast sorting method

Source: Internet
Author: User

4. Quick Sort Method

Code:

function Quick_sort ($arr) {
Determine if you need to proceed
$length = count ($arr);
if ($length <= 1) {
return $arr;
}
If there is no return, the number of elements in the array is 1 extra and needs to be sorted
Select a ruler
Select the first element
$base _num = $arr [0];
Iterates through all elements except the ruler, and fits into two arrays in relation to size
Initialize two arrays
$left _array = Array ();//less than the ruler
$right _array = Array ();//greater than the ruler
for ($i =1; $i < $length; $i + +) {
if ($base _num > $arr [$i]) {
Put in the left array
$left _array[] = $arr [$i];
} else {
Put it on the right
$right _array[] = $arr [$i];
}
}
The same sort method for the left and right arrays, respectively.
Call this function recursively and record the result
$left _array = Quick_sort ($left _array);
$right _array = Quick_sort ($right _array);
Merge left ruler right
Return Array_merge ($left _array, Array ($base _num), $right _array);
}

PHP four basic algorithm----fast sorting method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.