Write a sort algorithm (to write out the code) and say how to optimize it.

Source: Internet
Author: User

1<?PHP2 //Quick Sort3 functionPartition (&$arr,$low,$high)4 {5     $pivotkey=$arr[$low];6      while($low<$high) {7          while($low<$high&&$arr[$high] >=$pivotkey) {8             $high--;9         }Ten         $temp=$arr[$low]; One         $arr[$low] =$arr[$high]; A         $arr[$high] =$temp; -          while($low<$high&&$arr[$low] <=$pivotkey) { -             $low++; the         } -         $temp=$arr[$low]; -         $arr[$low] =$arr[$high]; -         $arr[$high] =$temp; +     } -     return $low; + } A  at /** - * @param $arr array - * @param $low Data Sort starting position (subscript) - * @param $high data sort End position (subscript) -  */ - functionQuick_sort (&$arr,$low,$high) in { -     if($low<$high) { to         $pivot= Partition ($arr,$low,$high); +Quick_sort ($arr,$low,$pivot-1); -Quick_sort ($arr,$pivot+ 1,$high); the     } * } $ Panax Notoginseng $arr=Array(10,9,8,7,6,5); -Quick_sort ($arr, 3,4); the Echo' <pre> '; + foreach($arr  as $v) { A     Echo $v.‘ <br/> '; the}


The algorithm is implemented by the recursive return of the method, its efficiency depends largely on the selection of reference elements, can choose the intermediate elements of the array, you can randomly get three elements, and then select the middle element (three number median method).
Another thing is that when we split up, if the length of the split sub-sequence is small (less than 5 to 20), the efficiency of the recursive sorting is not as fast as the insertion sort or the hill sort. So you can judge the length of the array, if it is less than 10, directly with the insertion sort, instead of recursively calling this quick sort.

The

writes out a sort algorithm (to write out the code) and says how to optimize it.

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.