插入排序:插入排序是简单直接的排序方式之一,将无序序列分成两块,左侧有序,右侧无序,然后将右侧的元素依次插入到左侧合适的位置,使得左侧元素有序。待右侧元素全部插入左侧,整个序列排序完成。
代码:
public void insertionSort() {
DataNode tempNode;
int j;
for (int i = 2; 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
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("Resultrn" + tempDataArray);
}// of insertionSortTest
运行结果:
------------------------insertionSort----------------------- I am a data array with 8 item. (-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 item. (-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 item. (-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 item. (-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 item. (-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 item. (-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 item. (-100,null) (1,for) (3,then) (5,if) (6,else) (7,case) (9,while) (10,switch) Result I am a data array with 8 item. (-100,null) (1,for) (3,then) (5,if) (6,else) (7,case) (9,while) (10,switch)



