常用排序算法之直接插入排序

直接插入排序

    插入排序可以分为直接插入排序、折半插入排序、希尔排序,他们的时间和空间复杂度请参考上一篇博客点击打开链接,本篇文章将介绍插入排序方法中的直接插入排序。
    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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值