forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request wangzheng0822#104 from iyoungm/master
php_12_sort_mergeSort
- Loading branch information
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
<?php | ||
|
||
$arr = [4, 5, 6, 1, 3, 2]; | ||
$length = count($arr); | ||
|
||
$p = 0; | ||
$r = $length - 1; | ||
|
||
$result = $this->mergeSort($arr, $p, $r); | ||
|
||
var_dump($result); | ||
|
||
|
||
//递归调用,分解数组 | ||
function mergeSort(array $arr, $p, $r) | ||
{ | ||
if ($p >= $r) { | ||
return [$arr[$r]]; | ||
} | ||
$q = (int)(($p + $r) / 2); | ||
|
||
$left = $this->mergeSort($arr, $p, $q); | ||
$right = $this->mergeSort($arr, $q + 1, $r); | ||
return $this->merge($left, $right); | ||
} | ||
|
||
//合并 | ||
function merge(array $left, array $right) | ||
{ | ||
$tmp = []; | ||
|
||
$i = 0; | ||
|
||
$j = 0; | ||
|
||
$leftLength = count($left); | ||
|
||
$rightLength = count($right); | ||
|
||
do { | ||
if ($left[$i] <= $right[$j]) { | ||
$tmp[] = $left[$i++]; | ||
} else { | ||
$tmp[] = $right[$j++]; | ||
} | ||
|
||
} while ($i < $leftLength && $j < $rightLength); | ||
|
||
|
||
$start = $i; | ||
$end = $leftLength; | ||
$copyArr = $left; | ||
|
||
if ($j < $rightLength) { | ||
$start = $j; | ||
$end = $rightLength; | ||
$copyArr = $right; | ||
} | ||
|
||
for (; $start < $end; $start++) { | ||
$tmp[] = $copyArr[$start]; | ||
} | ||
|
||
return $tmp; | ||
|
||
} |