Home > php教程 > PHP源码 > php基本排序

php基本排序

PHP中文网
Release: 2016-05-26 08:19:11
Original
1103 people have browsed it

[PHP]代码    

<?php
//参考这个网站的伪代码编写的
//http://www.php.cn/

$unsortList = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2];

// 冒泡排序
function bubbleSort($arr) {
	do {
		$swapped = false;
		for ($i = 1; $i < count($arr); $i++) {
			if ($arr[$i-1] > $arr[$i]) {
				$temp = $arr[$i-1];
				$arr[$i-1] = $arr[$i];
				$arr[$i] = $temp;
				$swapped = true;
			}
		}
	} while ($swapped);
	return $arr;	
}

// 选择排序
function selectSort($arr) {
	$minimumPosition = 0;
	$len = count($arr);
	for ($i = 0; $i < $len - 1; $i++) {		
		for ($j = $i + 1; $j < $len - $i; $j++) {
			if ($arr[$j] < $arr[$minimumPosition]) {
				$minimumPosition = $j;
			}
		}
		$temp = $arr[$i];
		$arr[$i] = $arr[$minimumPosition];
		$arr[$minimumPosition] = $temp;
	}
	return $arr;
}

// 插入排序
function insertSort1($arr) {
	$len = count($arr);		
	for ($i = 1; $i < $len; $i++) {
		$extractElement = $arr[$i];		
		for ($j = $i - 1; $j >= 0; $j--) {
			if ($arr[$j] > $extractElement) {
				$arr[$j+1] = $arr[$j];												
				$arr[$j] = $extractElement;
			}
		}			
	}
	return $arr;
}
/**
 * 插入排序
 * @param Array $a 无序集合
 * @return Array 有序集合
 */
function insertSort2($a) {
	$temp;
	$i;
	$j;
	$size_a = count($a);
	# 从第二个元素开始
	for ($i = 1; $i < $size_a; $i++) {			
		if ($a[$i] < $a[$i-1]) {			
			$j = $i; # 保存当前元素的位置
			$temp = $a[$i];	 # 当前元素的值	

			# 比较左边的元素,如果找到比自己更小的,向右移动元素,否则插入元素到当前位置
			while($j>0 && $temp<$a[$j-1]) {
			 	$a[$j] = $a[$j-1];
			 	$j--;
			}
			
			# 插入元素
			$a[$j] = $temp;
		}
	}
	return $a;
}

/**
 * 获取随机数
 * @param Integer $size 数量
 * @return Integer
 */
function randomNumber($size = 10) {
	$rand = array();
	srand(time(NULL));
	for ($i = 0; $i < $size; $i++) {
		array_push($rand, mt_rand(0,1000));		
	}
	return $rand;
}

//print_r(implode(",", bubbleSort($unsortList)));
//print_r(implode(",", selectSort($unsortList)));
//print_r(implode(",", insertSort1($unsortList)));
//print_r(implode(",", insertSort2($unsortList)));
Copy after login

                   

                   

Related labels:
php
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template