插入排序-直接插入排序

public static void insertSort(int[] a) { // 排序方法
		// 从头部第一个当做已经排好序的,把后面的一个一个的插到已经排好的列表中去。
		for (int i = 1; i < a.length; i++) {

			if (a[i] < a[i - 1]) {
				int j;
				int x = a[i]; // x为待插入元素
				a[i] = a[i - 1];

				// 通过循环,逐个后移一位找到要插入的位置。
				// 每次比对都将比对元素向后移一位
				// 比对成功后,插入元素
				for (j = i - 1; j >= 0 && x < a[j]; j--) {
					a[j + 1] = a[j];
				}
				a[j + 1] = x; // 插入
			}
		}
	}

解析版本:

     解析版本不用看,复制到eclipse中,直接运行,辅助理解。 

public class ParseInsertSort {
	public static void main(String[] args) {
		int a[] = { 3, 5, 1, 7, 2, 4, 9, 6, 10, 8 };
		System.out.print("初始值:");
		print(a);

		insertSort(a);
		
		System.out.print("排序后:");
		print(a);
	}

	public static void print(int a[]) { // 打印方法
		for (int i = 0; i < a.length; i++) {
			if (i == 0) {
				System.out.print("[");
			} else if (i == a.length - 1) {
				System.out.print(a[i] + "]");
				break;
			}
			System.out.print(a[i] + " ");
		}
	}

	public static void insertSort(int[] a) { // 排序方法
		// 从头部第一个当做已经排好序的,把后面的一个一个的插到已经排好的列表中去。
		System.out.println("  \r\n寻找待插入元素:");
		for (int i = 1; i < a.length; i++) {
			System.out.print("   当前数组:"); // 输出过程
			print(a); // 输出过程
			System.out.println("\t比较元素:" + " a[" + i + "]:" + i + "  a[" + (i - 1) + "]:" + a[i - 1]); // 输出过程

			if (a[i] < a[i - 1]) {
				int j;
				int x = a[i]; // x为待插入元素

				System.out.println("  确定待插入元素: 原a[" + i + "]:" + x + "\r\n  寻找插入位置:"); // 输出过程

				a[i] = a[i - 1];

				// 通过循环,逐个后移一位找到要插入的位置。
				// 每次比对都将比对元素向后移一位
				// 比对成功后,插入元素
				for (j = i - 1; j >= 0 && x < a[j]; j--) {
					System.out.print("   当前数组:"); // 输出过程
					print(a); // 输出过程
					System.out.println(" 待插入元素:原a[" + i + "]:" + x + "    比对元素:a[" + (j) + "]:" + a[j]); // 输出过程

					a[j + 1] = a[j];
				}
				a[j + 1] = x; // 插入
				System.out.println("  插入成功!\r\n");
				if (i != a.length - 1) {
					System.out.println("  寻找待插入元素:");
				}
			}
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值