ITeye博客

直接插入排序

jkbjxy · 2014-09-01 10:44 · 算法学习 · 编程语言 · 插入排序 · Markdown

public class InsertSort {

	/**
	 * 直接插入排序算法
	 * 将一个记录插入到已经排序好的有序表中
	 * @param args
	 */
	public static void main(String[] args){
		int num[] = {44,1,3,5,2,8,4,9,7,6,21,11,2,99};
		int temp,j;
		for(int i=1; i<num.length; i++){
			temp = num[i]; //设置为哨兵
			for(int n=0;n<num.length;n++){
				System.out.print(num[n]+"  ");
			}
			for(j=i-1;j>=0&&temp<num[j];j--){
				num[j+1] = num[j];
			}
			num[j+1] = temp;
			System.out.println("");
		}
		for(int n=0;n<num.length;n++){
			System.out.print(num[n]+"  ");
		}
	}
}

排序结果:

44  1  3  5  2  8  4  9  7  6  21  11  2  99  
1  44  3  5  2  8  4  9  7  6  21  11  2  99  
1  3  44  5  2  8  4  9  7  6  21  11  2  99  
1  3  5  44  2  8  4  9  7  6  21  11  2  99  
1  2  3  5  44  8  4  9  7  6  21  11  2  99  
1  2  3  5  8  44  4  9  7  6  21  11  2  99  
1  2  3  4  5  8  44  9  7  6  21  11  2  99  
1  2  3  4  5  8  9  44  7  6  21  11  2  99  
1  2  3  4  5  7  8  9  44  6  21  11  2  99  
1  2  3  4  5  6  7  8  9  44  21  11  2  99  
1  2  3  4  5  6  7  8  9  21  44  11  2  99  
1  2  3  4  5  6  7  8  9  11  21  44  2  99  
1  2  2  3  4  5  6  7  8  9  11  21  44  99  
1  2  2  3  4  5  6  7  8  9  11  21  44  99  

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。