插入排序Insertion sort

插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。 
插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序,折半插入排序留到“查找”内容中进行。 
  图1演示了对4个元素进行直接插入排序的过程,共需要(a),(b),(c)三次插入。

Image(6)

public class InsertSort {
	public static void main(String[] args) {
		int[] arr = {8, 2, 4, 9, 3, 6, 7, 10};
		insertSort(arr);
	}
	
	//辅助函数
	public static void dumpArray(int[] arr) {
		for(int index = 0; index < arr.length; index++) {
			System.out.print(arr[index] + " ");
		}
		System.out.println("");
	}
	
	public static void insertSort(int[] arr) {
		dumpArray(arr); //输出原始数组
		for(int index = 1; index < arr.length; index++) {
			int subIndex = index;
			int currentData = arr[index]; //等待插入的数据
			while((subIndex > 0) && arr[subIndex - 1] > currentData) {
				arr[subIndex] = arr[subIndex - 1];
				subIndex--;
			}
			arr[subIndex] = currentData; //插入到合适位置
			//每次排序后也输出
			dumpArray(arr);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值