Home  >  Article  >  Backend Development  >  PHP writing bubble sort PHP array bubble sort PHP bubble sort principle PHP is optimal for bubble sort

PHP writing bubble sort PHP array bubble sort PHP bubble sort principle PHP is optimal for bubble sort

WBOY
WBOYOriginal
2016-07-29 08:54:311239browse
<?php
function getRandArr(){
	$num = mt_rand(10,11);
	$arr = array();
	for($i = 0;$i < $num;$i++){
		$arr[$i] = mt_rand(100,100000);
	}

	return $arr;
}

//冒泡排序
function bubbleSort($arr,$asc = TRUE){
	$last_key = count($arr) - 1;

	if($asc == TRUE){
		//升序
		for($i = 0;$i <= $last_key;$i++){

			//获取已经排序号的key
			$sort_key = $last_key - $i;

			for($j = 0;$j < $sort_key;$j++){
				if($arr[$j] > $arr[($j + 1)]){
					//下一个大于上一个
					$temp = $arr[($j + 1)];
					$arr[($j + 1)] = $arr[$j];
					$arr[$j] = $temp;
				}
			}
		}
	}else{
		//降序
		for($i = $last_key;$i >= 0;$i--){
			
			//获取已经排序好的key
			$sort_key = $last_key - $i;

			for($j = $last_key;$j > $sort_key;$j--){
				if($arr[$j] > $arr[($j - 1)]){
					//下一个大于上一个
					$temp = $arr[($j - 1)];
					$arr[($j - 1)] = $arr[$j];
					$arr[$j] = $temp;
				}
			}
		}
	}

	return $arr;
}

$sort_arr = getRandArr();
var_dump(bubbleSort($sort_arr));

The above introduces how to write bubble sort in PHP, including bubble sort and PHP content. I hope it will be helpful to friends who are interested in PHP tutorials.

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