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

WBOY
Release: 2016-07-29 08:54:31
Original
1238 people have browsed it
<?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));
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!