插入排序(二)

/**
 * 
 * @author Administrator
 * 插入排序原理:对于给定的一组记录,初始时假设第一个记录自成一个有序序列,其余记录为无序序列;
 * 接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,
 * 直至最后一个记录插入到有序序列中为止;
 *从原数组第2个元素开始,遍历数组,依次把遍历到的元素按照一定的顺序插入到当前元素的小数组中(自己总结)
 *排序过程是一个挖坑填坑的过程
 */

public class InsertSort {
	public static void printArray(int a[]){
		for(int i=0;i<a.length;i++)
			System.out.print(a[i]);
	}

	public static void insertSort(int a[]){
		int n = a.length;
		int temp =0;
		for(int i=1;i<n;i++){
			int j=i;
			temp = a[j];
			while(j>=1&&a[j-1]>temp){	//原子数组中的元素后移,注意边界条件。这是一个挖坑的过程
				a[j] = a[j-1];
				j--;
			}
			a[j]=temp;	//填坑
		}
			
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[] ={5,4,3,2,1};
		insertSort(a);
		printArray(a);
	}

}

运行结果:

12345

 

posted @ 2015-09-04 20:56  CS408  阅读(132)  评论(0编辑  收藏  举报