简述
基本思想:希尔排序是把序列按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量的逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个序列恰好被分为一组,算法便终止。
我们用几张图片来理解
实战代码
/**
*********************
* Shell sort. We do not use sentries here because too many of them are need.
*********************
*/
public void shellSort() {
DataNode tempNode;
int[] tempJumpArray = { 5, 3, 1 };
int tempJump;
int p;
for (int i = 0; i < tempJumpArray.length; i++) {
tempJump = tempJumpArray[i];
for (int j = 0; j < tempJump; j++) {
for (int k = j + tempJump; k < length; k += tempJump) {
tempNode = data[k];
// Find the position to insert.
// At the same time, move other nodes.
for (p = k - tempJump; p >= 0; p -= tempJump) {
if (data[p].key > tempNode.key) {
data[p + tempJump] = data[p];
} else {
break;
} // Of if
} // Of for p
// Insert.
data[p + tempJump] = tempNode;
} // Of for k
} // Of for j
System.out.println("Round" + i);
System.out.println(this);
} // Of for i
}// Of shellSort
/**
*********************
* Test the method.
*********************
*/
public static void shellSortTest() {
int[] tempUnsortedKeys = { 5, 3, 6, 10, 7, 1, 9, 12, 8, 4 };
String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while", "throw", "until", "do" };
DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
System.out.println(tempDataArray);
tempDataArray.shellSort();
System.out.println("Result\r\n" + tempDataArray);
}// Of shellSortTest
运行结果
-------ShellSorTest-------
I am a data array with 10 items.
(5, if) (3, then) (6, else) (10, switch) (7, case) (1, for) (9, while) (12, throw) (8, until) (4, do)
Round0
I am a data array with 10 items.
(1, for) (3, then) (6, else) (8, until) (4, do) (5, if) (9, while) (12, throw) (10, switch) (7, case)
Round1
I am a data array with 10 items.
(1, for) (3, then) (5, if) (7, case) (4, do) (6, else) (8, until) (12, throw) (10, switch) (9, while)
Round2
I am a data array with 10 items.
(1, for) (3, then) (4, do) (5, if) (6, else) (7, case) (8, until) (9, while) (10, switch) (12, throw)
Result
I am a data array with 10 items.
(1, for) (3, then) (4, do) (5, if) (6, else) (7, case) (8, until) (9, while) (10, switch) (12, throw)