Ask a question about the quick Sort method

Source: Internet
Author: User
Ask a quick sort of question


------to solve the idea----------------------
Each execution is a local variable in the function body, unless it is a static or global variable that changes
------to solve the idea----------------------
This is a clear view.
print_r (Quick_sort (Array (6,1,5,8,7,4,2,3,0))); 
Function Quick_sort ($arr) {
//Determine whether you need to proceed with
$length = count ($arr) first;
if ($length <= 1) {
return $arr;
}
//If not returned, indicates that there are more than 1 elements in the array, you need to sort
//Select a ruler
//Select the first element
$base _num = $arr [0];
Iterate through all elements except the ruler, place the two array in the size relationship
//Initialize two arrays
$left _array = Array (),//less than the ruler's
$right _array = Array (),////greater than the ruler's
for ($i =1; $i < $length; $i + +) {
if ($base _num > $arr [$i]) {
//put left array
$left _array[] = $arr [$i];
} else {
//Put right array
$right _array[] = $arr [$i];
}
}
printf ("in[%s] b[%d] l[%s] r[%s]
", Join (', ', $arr), $base _num, join (', ', $left _array), join (', ', $ Right_array));
//The same sorting is done for the left and right groups
//recursively call this function 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);
}
in[6,1,5,8,7,4,2,3,0] b[6] l[1,5,4,2,3,0] r[8,7]
in[1,5,4,2,3,0] b[1] l[0] r[5,4,2,3]
in[5,4,2,3] b[5] l[4,2,3] r[]
in[4,2,3] b[4] l[2,3] r[]
in[2,3] b[2] l[] r[3]
in[8,7] b[8] l[7] r[]
  • 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.