Home >php教程 >PHP源码 >php冒泡排序和快速排序

php冒泡排序和快速排序

PHP中文网
PHP中文网Original
2016-05-25 17:10:53986browse

php代码

<?php
$arr = array(12,1,5,88,35,0,18,100,50,21,28,7,9,9.5);

//交换两值
function swap(&$m, &$n){
	$temp = $m;
	$m = $n;
	$n = $temp;

	/* 如数组中有小数时,以下方法会省略小数点后面的数
	$m = $m ^ $n;
	$n = $m ^ $n;
	$m = $m ^ $n;
	*/
}

//冒泡排序
function bubbleSort($arr){
	if(!is_array($arr)) return $arr;
	$count = count($arr);
	for($i=1; $i<$count; $i++){
		for($j=0; $j $arr[$j+1]){
				/*
				$temp = $arr[$j];
				$arr[$j] = $arr[$j+1];
				$arr[$j+1] = $temp;
				*/
				/*
				$arr[$j] = $arr[$j] + $arr[$j+1];
				$arr[$j+1] = $arr[$j] - $arr[$j+1];
				$arr[$j] = $arr[$j] - $arr[$j+1];
				*/
				/*
				$arr[$j] = $arr[$j] ^ $arr[$j+1];
				$arr[$j+1] = $arr[$j] ^ $arr[$j+1];
				$arr[$j] = $arr[$j] ^ $arr[$j+1];
				*/
				swap($arr[$j], $arr[$j+1]);
			}
		}
	}
	return $arr;
}

$arr2 = bubbleSort($arr);
echo implode(&#39;,&#39;, $arr2).&#39;&#39;;

//冒泡排序
function bubbleSort2($arr){
	if(!is_array($arr)) return $arr;
	$count = count($arr);
	for($i=0; $i<$count-1; $i++){
		for($j=$i+1; $j<$count; $j++){
			if($arr[$i] < $arr[$j]){
				/*
				$arr[$i] = $arr[$i] + $arr[$j];
				$arr[$j] = $arr[$i] - $arr[$j];
				$arr[$i] = $arr[$i] - $arr[$j];
				*/
				swap($arr[$i], $arr[$j]);
			}
		}
	}
	return $arr;
}
$arr3 = bubbleSort2($arr);
echo implode(&#39;,&#39;, $arr3).&#39;&#39;;;

//快速排序
function quickSort($arr){
	if(!is_array($arr)) return $arr;
	$len=count($arr);
	for($i=0; $i<$len; $i++){
		$min = $arr[$i];
		for($j=$i+1; $j $arr[$j]){
				$temp = $arr[$i];
				$arr[$i] = $arr[$j];
				$arr[$j] = $temp;
			}
		}
		$min = $arr[$j];
	}
	return $arr;
}
$arr4 = quickSort($arr);
echo implode(&#39;,&#39;, $arr4);
?>

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
Previous article:PHP 截取中文字符Next article:php下载程序