---
title: "直接插入排序"
author: "jkbjxy"
date: "2014-09-01T10:44:01Z"
tags: ["插入排序"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-09-01T17:03:46Z"
id: 2111432
url: "https://jkhhuse.iteye.com/blog/2111432"
---

```
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  
```