简述
插入排序原理很简单,将一组数据分成两组,我分别将其称为有序组与待插入组。每次从待插入组中取出一个元素,与有序组的元素进行比较,并找到合适的位置,将该元素插到有序组当中。就这样,每次插入一个元素,有序组增加,待插入组减少。直到待插入组元素个数为0。当然,插入过程中涉及到了元素的移动。
特点
1.代码非常短,因为是简单直接的排序方式
2.每次要保证前i个数据是有顺序的
3.先做简单的事情(第一轮最多有一次移动),在做麻烦的事情(最后一轮有n-1次移动)
4.下标0的数据为岗哨,与前面的顺序查找和折半查找同理,比其他排序方式多用一个空间
5.又见this
6.tempNode只分配了引用(指针)的空间,并未new
代码
代码如下(示例):
/**
* *************************
* Insertion sort.data[0] does not store a valid data. data[0].key should be samller than valid key.
* *************************
*/
public void insertionSort() {
DataNode tempNode;
int j;
for (int i = 2; i < length; i++) {
tempNode = data[i];
// Find the position to insert.
// At the same time, move other nodes.
for (j = i - 1; data[j].key > tempNode.key; j--) {
data[j + 1] = data[j];
} // Of for j
// Insert.
data[j + 1] = tempNode;
System.out.println("Round " + (i - 1));
System.out.println(this);
} // Of for i
}// Of insertionSort
/**
*********************
* Test the method.
*********************
*/
public static void InsertionSortTest() {
int[] tempUnsortedKeys = { -100, 5, 3, 6, 10, 7, 1, 9 };
String[] tempContents = { "null", "if", "then", "else", "switch", "case", "for", "while" };
DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
System.out.println(tempDataArray);
tempDataArray.insertionSort();
System.out.println("Result\r\n" + tempDataArray);
}// Of insertionSortTest
运行结果
-------InsertionSorTest-------
I am a data array with 8 items.
(-100, null) (5, if) (3, then) (6, else) (10, switch) (7, case) (1, for) (9, while)
Round 1
I am a data array with 8 items.
(-100, null) (3, then) (5, if) (6, else) (10, switch) (7, case) (1, for) (9, while)
Round 2
I am a data array with 8 items.
(-100, null) (3, then) (5, if) (6, else) (10, switch) (7, case) (1, for) (9, while)
Round 3
I am a data array with 8 items.
(-100, null) (3, then) (5, if) (6, else) (10, switch) (7, case) (1, for) (9, while)
Round 4
I am a data array with 8 items.
(-100, null) (3, then) (5, if) (6, else) (7, case) (10, switch) (1, for) (9, while)
Round 5
I am a data array with 8 items.
(-100, null) (1, for) (3, then) (5, if) (6, else) (7, case) (10, switch) (9, while)
Round 6
I am a data array with 8 items.
(-100, null) (1, for) (3, then) (5, if) (6, else) (7, case) (9, while) (10, switch)
Result
I am a data array with 8 items.
(-100, null) (1, for) (3, then) (5, if) (6, else) (7, case) (9, while) (10, switch)