Merge Sort in PHP - Php

Merge Sort in PHP

Snippet Code


  
Rate this page :
  [ 0 votes]

Here Sorting the array using by merge sort in php

<?php function sorting($array) { if(count($array) == 1 ) { return $array; } $cen = count($array) / 2; $lhs = array_slice($array, 0, $cen); $rhs = array_slice($array, $cen); $lhs = sorting($lhs); $rhs = sorting($rhs); return merge($lhs, $rhs); } function merge($lhs, $rhs) { $res = array(); while (count($lhs) > 0 amp&count($rhs) > 0) { if($lhs[0] > $rhs[0]) { $res[] = $rhs[0]; $rhs = array_slice($rhs , 1); } else { $res[] = $lhs[0]; $lhs = array_slice($lhs, 1); } } while (count($lhs) > 0) { $res[] = $lhs[0]; $lhs = array_slice($lhs, 1); } while (count($rhs) > 0) { $res[] = $rhs[0]; $rhs = array_slice($rhs, 1); } return $res; } $array = array(3,18,21,9,7,100); print_r($array); $array =sorting($array); print_r($array); ?>

Tags


Ask Questions

Ask Question