选择算法
来源:互联网 发布:网络暴力英文ppt 编辑:程序博客网 时间:2024/06/08 07:03
选择算法(遍历所有数,选择比较最小的数在最前面,依次类推)
1.遍历所有的数,默认第一个数是最小值。
2.遍历最小值后面的数,和最小值比较,若是遍历数比最小值小,则互换位置,确定最新的最小值。
3.重复上面的操作。
C++的写法:
#include <iostream>#include <algorithm>using namespace std;//arr[]是数组,n是数组的长度void selectionSort( int arr[], int n) { for (int i = 0; i < n ; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[mnIndex]) minIndex = j; swap(arr[i], arr[minIndex]); }}
PHP的写法:
//$arr是数组,这里数组长度直接用count()方法获取function selectSort($arr) { for ($i = 0; $i < count($arr) - 1; $i++) { for ($j = $i + 1; $j < count($arr); $j++) { if ($arr[$j] < $arr[$i]) {$temp = $arr[$j];$arr[$j] = $arr[$i];$arr[$i] = $temp; }} } return $arr;}
事实上php这里应该优化一下,确定最小值的下标在进行交换才比较合适,优化后的代码为:
function selectSort($arr) { for ($i = 0; $i < count($arr) - 1; $i++) { $p = $i; for ($j = $i + 1; $j < count($arr); $j++) { if ($arr[$j] < $arr[$p]) {$p = $j;} } if ($p != $i) {$temp = $arr[$p];$arr[$p] = $arr[$i];$arr[$i] = $temp; }} return $arr;}只是改变下标,等确定下标最小数后在进行交换,减少运算量。
阅读全文
0 0
- “选择算法”
- 算法 选择
- 选择算法
- 选择算法
- 选择算法
- 选择算法
- 选择算法
- 选择算法
- 算法:选择
- 选择算法
- 选择算法
- 排序算法 选择算法
- 算法:选择排序算法。
- 选择算法(选择排序)
- 算法笔记(选择算法)
- 算法(选择排序的算法)
- 算法_选择排序算法
- 查找算法---快速选择算法
- maven的resources介绍
- Mysql优化专题
- 【洛谷1640】[SCOI2010]连续攻击游戏
- JVM类加载原理学习笔记
- 补题补题补题~~~~really big numbers
- 选择算法
- 编译内核提示mkimage command not found – U-Boot images will not be built
- Java垃圾收集学习笔记
- 华为机试:计算字符串的距离、24点游戏算法
- Http状态码
- 【图论经典题】战争
- 常见的神经网络的优化方法
- JMS发布订阅(Pub/Sub)模式示例
- 前端面试题总结HTML CSS部分