Relive PHP's quick sort

Source: Internet
Author: User



Rationale: Select any element in the current array (usually the first one) as the standard, create a new two empty array before and after the current array, and then iterate through the current array, if the element value in the array is less than or equal to the first element value, put it in an empty array, or put it behind an empty array.


1 / / quick sort
  2 function quick_sort($arr) {
  3 / / Get the number of array units
  4 $count = count($arr);
  5 / / determine the length of the array
  6 if ($count <= 1) {
  7 return $arr;
  8 } else {
  9 //Define two empty arrays
10 $before = $after = array();
11 // iterate over the array
12 for ($i=1; $i < $count; $i++) {
13 // judge by the first element
14 if ($arr[$i] <= $arr[0]) {
15 $before[] = $arr[$i];
16 } else {
17 $after[] = $arr[$i];
18 }
19 }
20 //Recursive call
21 $before = quick_sort($before);
22 $after = quick_sort($after);
23 //Merge array
24 return array_merge($before, array($arr[0]), $after);
25 }
26 }
27 //test
28 $arr = array(16, 9, 3, 12, 88, 19, 18, 16);
29 var_dump(quick_sort($arr));    
  



Relive PHP's quick sort


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.