java插入排序(最精简代码)

package com.cn.sort;

public class InsertSort {
	public void insertSort(int[] array, int first, int last) {
		int temp, i, j;
		for (i = first + 1; i <= last - 1; i++) {// 默认以第一个数为有序序列,后面的数为要插入的数。
			temp = array[i];
			j = i - 1;
			while (j >= first && array[j] > temp) {// 从后进行搜索如果搜索到的数小于temp则该数后移继续搜索,直到搜索到小于或等于temp的数即可
				array[j + 1] = array[j];
				j--;
			}
			array[j + 1] = temp;
			// 打印每次排序结果
			for (int m = 0; m <= array.length - 1; m++) {
				System.out.print(array[m] + "\t");
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {
		InsertSort insertSort = new InsertSort();
		int[] array = { 5, 69, 12, 3, 56, 789, 2, 5648, 23 };
		insertSort.insertSort(array, 0, array.length);// 注意此处是0-9而不是0-8
		for (int i = 0; i <= array.length - 1; i++) {
			System.out.print(array[i] + "\t");
		}
	}
}

转载于:https://my.oschina.net/mkh/blog/81236

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值