php sort notes - merge sort

Merge sort

The array is divided into left and right parts, respectively, and then sorting, merging finally

 public function _sort(&$arr,$left,$right){

        IF ( $ left < $ right ) {
             // if you do less than the right, remove the intermediate values, rounding. Enter a recursive process. 
            MID $ = Floor (( $ left + $ right ) / 2 );

            $this->_sort($arr,$left,$mid);
            $this->_sort($arr,$mid+1,$right);
            $this->_merge($arr,$left,$mid,$right);
        }
    }

    public function _merge(&$arr,$left,$mid,$right){
        $i = $left;
        $j = $mid+1;
        $tmp = [];

        // The two minimum value taken out, placed in a temporary array. If the cross-border out of the loop. 
        the while ( $ I <= $ MID && $ J <= $ right ) {
             IF ( $ ARR [ $ I ] < $ ARR [ $ J ]) {
                 $ tmp [] = $ ARR [ $ I ++ ];
            }else{
                $tmp[]=$arr[$j++];
            }
        }

        // determination, whether there is left, there will be left in the remaining portion tmp put all 
        the while ( $ I <= $ MID ) {
             $ tmp [] = $ ARR [ $ I ++ ];
        }
        // determination, the right exists, the remaining portion of the right side there will put all tmp in 
        the while ( $ J <= $ right ) {
             $ tmp [] = $ ARR [ $ J ++ ];
        }
        // copy temporary data in the array ARR to $ 
        for ( $ K = 0, $ len = COUNT ( $ tmp ); $ K < $ len ; $ K ++ ) {
             $ ARR [ $ left + $ K ] = $ tmp [ $ K ];
        }
       

    }

 

Guess you like

Origin www.cnblogs.com/liyante/p/11127441.html