1

PHP之选择排序的实现

 2 years ago
source link: https://panda843.github.io/article/3434685696.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PHP之选择排序的实现

发表于 2017-12-28 | 分类于 开发 | | 浏览4 次 | 字数统计: 322 | 阅读时长 ≈ 1

选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。

<?php
//选择排序
function selectSort($arr) {
//双重循环完成,外层控制轮数,内层控制比较次数
$len=count($arr);
for($i=0; $i<$len-1; $i++) {
//先假设最小的值的位置
$p = $i;
for($j=$i+1; $j<$len; $j++) {
//$arr[$p] 是当前已知的最小值
if($arr[$p] > $arr[$j]) {
//比较,发现更小的,记录下最小值的位置;并且在下次比较时采用已知的最小值进行比较。
$p = $j;
}
}
//已经确定了当前的最小值的位置,保存到$p中。如果发现最小值的位置与当前假设的位置$i不同,则位置互换即可。
if($p != $i) {
$tmp = $arr[$p];
$arr[$p] = $arr[$i];
$arr[$i] = $tmp;
}
}
//返回最终结果
return $arr;
}
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
Error: API rate limit exceeded for 141.164.63.164. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK