排序算法-插入排序

本文深入探讨了一种插入排序算法的实现方式,通过具体代码展示了如何通过比较和元素交换完成数组排序的过程,并与另一种常见的插入排序实现进行了效率对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package insert;

import util.ArrayUtil;

public class InsertSort {

	public static void main(String[] args) {
		/**
		 * 判断索引为j和索引为j-k的值,如果索引为j的值大于索引为j-k的值,就不用换为位置,直接退出内循环,否则就交换位置, 直到j-k为0。
		 * 
		 */
		int[] intArrayForSort = ArrayUtil.getRandomArray();

		int i = 1, k, j = 1;
		long t = System.currentTimeMillis();
		for (i = 1; i < intArrayForSort.length; i++) {
			int minValue = intArrayForSort[j];// 假设索引为j的数字是最小的。
			k = 1;
			do {
				if (minValue < intArrayForSort[j - k]) {// intArrayForSort[j -
														// k]大于【临时最小值】,
														// 但【临时最小值】要插入的位置并不一定就在这个位置,所以要互换他们的位置。
					// **********begin*************
					int temp = intArrayForSort[j - k + 1];// j - k + 1最不好理解的地方
					intArrayForSort[j - k + 1] = intArrayForSort[j - k];
					intArrayForSort[j - k] = temp;
					// ***********end**************
					// begin和end的代码块目的是将2个数字的位置互换。
				} else {// 临时最小值比已经排序好的数组中的最大值还大或者相同,直接退出内循环。
					break;
				}
				k++;
			} while ((j - k) >= 0);
			// 内循环的作用是:判断索引为j-k的值是否比 【临时的最小值 】大。
			j++;
		}
		System.out.println("\r<br>执行耗时 : " + (System.currentTimeMillis() - t)
				/ 1000f + " 秒 ");
		for (int printI = 0; printI < intArrayForSort.length; printI++) {
			// System.out.println(intArrayForSort[printI]);
		}

		InsertSort1(null);
	}

	/*
	 * 百度百科的参考例子。例子是找到需要的插入的位置的索引,然后将保存起来的值插进去。 而我的这个是每次都对比最小值,然后将2个值互换。 *
	 */

	public static void InsertSort1(int[] a) {
		a = ArrayUtil.getRandomArray();
		if (a != null) {
			long t = System.currentTimeMillis();
			for (int i = 1; i < a.length; i++) {
				int temp = a[i], j = i;// 将需要插入的数值保存起来
				if (a[j - 1] > temp) {
					// 将符合条件的数往后挪。符合的条件包括:1、需要插入的数值要比需要挪的最后一个数字小
					// 2、往后挪的最后一个数字的索引必须大于0
					while (j >= 1 && a[j - 1] > temp) {
						a[j] = a[j - 1];// 数值往后挪
						j--;
					}
					a[j] = temp;
				}
			}
			System.out.println("\r<br>执行耗时 : "
					+ (System.currentTimeMillis() - t) / 1000f + " 秒 ");
		} else {
			System.out.print("array hasn't bean inited!");
		}
	}

}

效率比百度百科的差了N百倍!!!!百度百科的只需要查找合适的一个索引即可,而我的需要将子数组往后挪动。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值