三、插入排序
来源:互联网 发布:培训管理数据流程图 编辑:程序博客网 时间:2024/06/09 23:26
1、算法原理
插入排序是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据。此算法适用于少量数据的排序,时间复杂度为O(n^2),空间复杂度为O(1)。插入排序是稳定的排序算法。
2、代码实现
(1)JAVA实现
注:本程序设计生成10个随机数,再对这10个随机数进行从小到大的插入排序
/* * 排序算法:插入排序 * 作者:xiaoxiao * 日期:2016-03-17 */import java.util.Random;public class InsertSort { public static void main(String[] args) { //定义可以存10个数的数组 int[] arr = new int[10]; int[] rs = new int[10]; init(arr); System.out.print("排序前:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + ", "); } System.out.println(); rs = insertSort(arr); System.out.print("排序后:"); for (int i = 0; i < rs.length; i++) { System.out.print(rs[i] + ", "); } } public static void init(int[] a) { Random r = new Random(); for (int i = 0; i < a.length; i++) { a[i] = r.nextInt(100); } } public static int[] insertSort(int[] a) { if (a == null || a.length < 2) { return a; } int tmp; for (int i = 1; i < a.length; i++) { //对前i-1个数据进行逐一遍历比较,将第i个数插入到恰当位置 for (int j = i; j > 0; j--) { if (a[j] < a[j - 1]) { tmp = a[j]; a[j] = a[j - 1]; a[j - 1] = tmp; } else { break; } } } return a; }}
运行结果:
(2)PHP实现
注:本程序设计随机生成10~20个1~100的数,再对这些数进行从小到大的插入排序
<!--Method:插入排序Author: xiaoxiaoDate: 2016-03-17--><?php echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";//如果涉及到PHP网页中文乱码问题,加上该行 function InsertSort($a){ $length = count($a); for($i = 1; $i < $length; $i++){ //对第i+1~$length的数字进行查找,找到最小数字对应的坐标 for ($j = $i; $j > 0; $j--) { if ($a[$j] < $a[$j-1]) { $temp = $a[$j]; $a[$j] = $a[$j-1]; $a[$j-1] = $temp; } else{ break; } } } return $a; } $a = array(); $nums = mt_rand(10,20); for ($i = 0; $i < $nums; $i++) { array_push($a, mt_rand(1,100)); } echo "待排序的数有".$nums."个!<br />"; echo "排序前: "; for($i = 0; $i < count($a); $i++){ echo $a[$i]; echo ", "; } echo "<br />"; echo "排序后: "; $b = InsertSort($a); for($i = 0; $i < count($b); $i++){ echo $b[$i]; echo ", "; }?>
运行结果:
阅读全文
0 0
- 排序三 插入
- 三、插入排序
- 三 插入排序
- 三、插入排序
- 排序算法三:插入排序
- 排序之三:插入排序
- 排序之三:插入排序
- 排序三 直接插入排序
- 排序算法(三)-插入排序
- 排序(三):插入排序
- 排序三 直接插入排序
- 算法学习(三)--插入排序
- C#算法----(三)插入排序
- 直接插入排序--学习(三)
- 算法整理(三):插入排序
- 插入排序三种实现
- C实现三种插入排序-简单插入排序、二分插入排序、希尔插入排序
- 排序算法系列三(插入排序)
- Appium--键盘操作 KEYCODE
- android 正确监听并拦截软键盘的退格键
- 报错解决:No Hibernate Session bound to thread, and configuration does not allow creation of non-transact
- vue自定义指令-vue-reclick
- linux下mysql 5.1 和 5.7的安装
- 三、插入排序
- 抽象类详解
- Python获取并输出当前日期时间
- js对时间日期的封装
- No Hibernate Session bound to thread, and configuration does not allow create解决方案
- shuffle 调优之条件map端内存缓存与reduce端内存占比
- 读书笔记《我所理解的cocos2dx》
- python_format
- 仿京东分类页面侧边listview的点击滑动