直接插入排序算法

package cn.xingxing.datastructure.sort;

/**
 * 直接插入排序算法
 * 
 * <pre>
 * 直接插入排序算法的思想是:顺序地把待排序的数据元素按其关键字值的大小插入到已排序数据元素子集合的适当位置。
 * 子集合的数据元素个数从只有一个数据元素开始逐次增大,当子集合大小与最终集合大小相同时排序完毕。
 * 初始关键字序列 [64] 5 7 89 6 24
 * 第一次排序  【 5 64】 7 89 6 24
 * 第2次排序  [5 7 64] 89 6 24
 * 第3次排序 [5 7 64 89 ] 6 24
 * 第4次排序[5 6 7 64 89] 24
 * 第5次排序[5 6 7 24 64 89]
 * []为排好序的
 * </pre>
 * 
 * @author icecookstar
 * 
 */
public class InsertSort {

	public static void insertSort(int[] a) {
		for (int i = 0; i < a.length - 1; i++) {
			int temp = a[i + 1];
			int j = i;
			while (j > -1 && temp < a[j]) {
				a[j + 1] = a[j];
				j--;
			}
			a[j + 1] = temp;

		}
		for (int i : a)
			System.out.println(i);
	}

	public static void main(String[] args) {

		int N = 100;
		int a[] = new int[N];
		for (int i = 0; i < 20; i++) {
			a[i] = (int) (Math.random() * N);
		}
		insertSort(a);
	}

}



   
posted @ 2012-10-02 21:58  段星星  阅读(174)  评论(0编辑  收藏  举报