Please explain the process of recursion in detail.
function Al_merge ($arrA, $arrB) {
$arrC = array(); while(count($arrA)&&count($arrB)){ $arrC[]=$arrA['0']<$arrB['0']?array_shift($arrA):array_shift($arrB); } return array_merge($arrC,$arrA,$arrB);}function al_merge_sort($arr){ $len = count($arr); if($len<=1) return $arr; $mid = intval($len/2); $left_arr = array_slice($arr,0,$mid); $right_arr = array_slice($arr,$mid); $left_arr = al_merge_sort($left_arr); $right_arr = al_merge_sort($right_arr); $arr = al_merge($left_arr,$right_arr); return $arr;}$arr=array(5,7,8,3);print_r(al_merge_sort($arr));
Reply content:
Please explain the process of recursion in detail.
function Al_merge ($arrA, $arrB) {
$arrC = array(); while(count($arrA)&&count($arrB)){ $arrC[]=$arrA['0']<$arrB['0']?array_shift($arrA):array_shift($arrB); } return array_merge($arrC,$arrA,$arrB);}function al_merge_sort($arr){ $len = count($arr); if($len<=1) return $arr; $mid = intval($len/2); $left_arr = array_slice($arr,0,$mid); $right_arr = array_slice($arr,$mid); $left_arr = al_merge_sort($left_arr); $right_arr = al_merge_sort($right_arr); $arr = al_merge($left_arr,$right_arr); return $arr;}$arr=array(5,7,8,3);print_r(al_merge_sort($arr));
Alas, you downvote the big real also not too impatient. Let's just say that you have 3 main questions about the main theme:
- See your profile in a lot of problems in fact, only need to carefully debug to solve, do not have to specifically ask a question.
- No use of search engines. Programmers are very fond of sharing knowledge, so no matter what syntax to explain, algorithm or library blog are very many.
- This problem is best in the SF sub-station 101 inside the question. When it comes to SF, it is recommended to use markdown typesetting.
Back to the question above, this sort is called merge sort, the algorithm idea is called divide and conquer method. You can find a lot of information by simply moving your finger on the search engine.
- The first is to
$arr
split into two arrays $left_arr
, $right_arr
.
- These arrays are then called again
al_merge_sort()
, in which the entire array is continuously split, and then split, while the process is constantly being called.
- So hack it all the way. The array will only have one element left in the day. An element does not have to be sorted and returned directly.
- At this point, we want to
al_merge_sort
return all the arrays that have been sorted in order.
- Then call
al_merge()
, let it from small to general two has been ordered array from small to large mixed together.
- In this way, a new sorted array is formed, well, returned. Go back up and repeat the fourth step.
- Always go to the top, that is, the last line of your code is called, is a well-ordered array.