Home >php教程 >PHP源码 >PHP快速排序算法(非递归)实现

PHP快速排序算法(非递归)实现

PHP中文网
PHP中文网Original
2016-05-23 16:41:022391browse

php代码

<?php

$i = 100;
while($i > 0){
	if($i > 30){
		$test[] = mt_rand($i - 30, $i--);
	}else{
		$test[] = mt_rand(1, $i--);
	}
}
//shuffle($test);
echo count($test), "\n";

//sort($test);
echo implode(", ", $test), "\n\n";
$t1 = microtime(true);

quicksort($test);
echo implode(", ", $test), "\n\n";
echo microtime(true) - $t1, "<br>\n";



function quicksort(array &$sort){
	$end = count($sort);
	if(--$end < 1){
		return;
	}

	$beg = 0;
	$stack = array();

	while(true){
		$i = $beg;
		$l = $end;
		$o = $sort[
			$x = mt_rand($i, $l)
		];

		while($i < $l){
			// 左边大于的
			if($sort[$i] > $o){
				while($i < $l){
					// 右边小于等于的
					if($sort[$l] <= $o){
						$tmp = $sort[$i];
						$sort[$i] = $sort[$l];
						$sort[$l] = $tmp;
						$i++; $l--;
						continue 2;
					}
					$l--;
				}
				goto re;
			}
			$i++;
		}
		if($sort[$i] < $o){
			$sort[$x] = $sort[$i];
			$sort[$i] = $o;
		}
//		echo $i, ", ", $l, "; ", $beg, ", ", $end, "\n";

	re:
		// 保存右边
		if($i < $end){
			$stack[] = $i;
			$stack[] = $end;
		}
		if(--$i > $beg){
			$end = $i; // 继续左边
		}elseif($stack){
			// 返回继续右边
			$end = array_pop($stack);
			$beg = array_pop($stack);
		}else{
			break;
		}
	}
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn