PHP 抉择排序 算法 经典面试题

WBOY
Release: 2016-06-13 12:49:30
Original
907 people have browsed it

PHP 选择排序 算法 经典面试题

<?php
$unsorted = array();

for ($i = 0; $i < 10; $i++) {
	$unsorted[] = rand(0,1000);
}

print "Unsorted Array. <br />";
print implode(',', $unsorted);

print "<br />";

print "Sorted Array. <br />";
$sort = select_sort($unsorted);
print implode(',',$sort);

/**
	selection sort
	1. 找到数组最小的数
	2. 与第一个数交换
	3. 重复余下的元素
*/
function select_sort ($arr = array()) {
	$min = false;
	$n = count($arr);
	
	for ($i = 0; $i < $n; $i++) {
		$min = $i;
		for ($j = $i + 1; $j < $n; $j++) {
			if ($arr[$j] < $arr[$min]) {
				$min = $j;
			}									
		}
		// $tmp = $arr[$min];  
		// $arr[$min] = $arr[$i];  
		// $arr[$i] = $tmp; 
		list($arr[$min],$arr[$i]) = array($arr[$i],$arr[$min]);
	}

	return $arr;
	
}
Copy after login

?

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!