常用排序算法之直接插入排序
来源:互联网 发布:鹰眼摄像头监控软件 编辑:程序博客网 时间:2024/05/17 09:35
直接插入排序
插入排序可以分为直接插入排序、折半插入排序、希尔排序,他们的时间和空间复杂度请参考上一篇博客点击打开链接,本篇文章将介绍插入排序方法中的直接插入排序。
1、思想:直接插入排序的思想就是依次将元素插入到一个有序序列中。假设有待排序列R[0,i-1],将其分为两部分:有序区R[0,j-1],无序区R[j,i-1],如图1所示。排序的过程就是将无序区R[j,i-1]中的元素逐一插入到有序区R[0,j-1]中。假设现有待排序列 { 1, 5, 3, 4, 8, 9, 2 },排序过程如图2所示。
图1
图2
2、代码实现(java)
package sort.baohuajie;import java.util.Arrays;/** * @author 包华杰 * 2017年12月3日 * * * 这里使用两种方法实现。本人认为,第二种方法更能体现插入排序的思想 */public class DirectInsertSort {public static void directInsertSort1(int[] array) {int temp;int time = 0;for (int i = 1; i < array.length; i++) {for (int j = i; j > 0; j--) {if (array[j] < array[j - 1]) {temp = array[j - 1];array[j - 1] = array[j];array[j] = temp;}time++;System.out.println("第" + time + "次排序结果:"+ Arrays.toString(array));}}}public static void directInsertSort2(int[] array) {int temp=0;int time = 0;int j;for (int i = 1; i < array.length; i++) {temp=array[i];j=i-1;/** * 用temp和array[j]进行比较,如果temp小于array[j],就让array[j]后移一个位置。 * 直到temp>=array[j]或者j<0 * 最后j+1的位置就是temp要插入的位置 */while(j>=0 && temp<array[j]){array[j+1]=array[j];j--;}array[j+1]=temp;System.out.println("第" + i + "次排序结果:"+ Arrays.toString(array));}}public static void main(String[] args) {//int[] array = { 1, 5, 3, 4, 2 ,0};int[] array = { 58,46,71,95,84,25,37,58,63,12 };directInsertSort2(array);}}
3、执行结果
第1次排序结果:[46, 58, 71, 95, 84, 25, 37, 58, 63, 12]第2次排序结果:[46, 58, 71, 95, 84, 25, 37, 58, 63, 12]第3次排序结果:[46, 58, 71, 95, 84, 25, 37, 58, 63, 12]第4次排序结果:[46, 58, 71, 84, 95, 25, 37, 58, 63, 12]第5次排序结果:[25, 46, 58, 71, 84, 95, 37, 58, 63, 12]第6次排序结果:[25, 37, 46, 58, 71, 84, 95, 58, 63, 12]第7次排序结果:[25, 37, 46, 58, 58, 71, 84, 95, 63, 12]第8次排序结果:[25, 37, 46, 58, 58, 63, 71, 84, 95, 12]第9次排序结果:[12, 25, 37, 46, 58, 58, 63, 71, 84, 95]
【上一篇】常用排序算法
【下一篇】常用排序算法之折半插入排序
阅读全文
0 0
- 常用排序算法之直接插入排序
- 常用排序算法之直接插入排序
- 常用算法总结之排序(七)---直接插入排序
- 常用的排序算法之直接插入排序java版
- Java常用排序算法之直接插入排序
- JAVA常用排序算法之直接插入排序
- 算法-插入排序之直接插入排序
- 排序算法-插入排序之直接插入
- 常用排序算法-直接插入排序
- 排序算法之直接插入排序算法
- 算法之直接插入排序
- 排序算法之直接插入
- 【算法】之直接插入排序
- 常用内部排序算法之四:简单选择排序、直接插入排序和冒泡排序
- 排序算法之直接插入排序
- java排序算法之直接插入排序
- 排序算法之直接插入排序
- 【排序算法】之直接插入排序
- easyui--3.layout
- ctf密码学——围在栅栏里的爱
- Pascal程序笔迹:快速幂
- @SerializedName
- 卷土重来:谷歌推出Datally新应用,适应中国消费市场
- 常用排序算法之直接插入排序
- easyui--4.tree
- PermissionsDispatcher
- 我(程序员?)
- ubuntu17.04中锐捷客户端登录问题
- 541. Reverse String II
- java之IO流-字节流
- EventBus3.0的简单实用
- 携程反爬中的Eleven参数-反爬与反反爬的奇技淫巧