希尔排序也是一种插入排序,它是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序,同时该算法是冲破O(n2)的第一批算法之一。希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
代码如下:
/**
* @Description: 希尔排序
* @Param: []
* @return: void
*/
public void shellSort() {
DataNode tpNode;
//设置间隔
int[] tpJumpArray = {5, 3, 1};
int tpJump;
int p;
for (int i = 0; i < tpJumpArray.length; i++) {
tpJump = tpJumpArray[i];
for (int j = 0; j < tpJump; j++) {
for (int k = j + tpJump; k < length; k += tpJump) {
tpNode = data[k];
//从当前节点往前比较排序,直接插入排序
for (p = k - tpJump; p >= 0; p -= tpJump) {
if (data[p].key > tpNode.key) {
data[p + tpJump] = data[p];
} else {
break;
}
}
data[p + tpJump] = tpNode;
}
}
System.out.println("Round " + i);
System.out.println(this);
}
}
/**
* @Description: 希尔排序测试
* @Param: []
* @return: void
*/
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);
}
public static void main(String[] args) {
System.out.println("\r\n-------sequentialSearchTest-------");
sequentialSearchTest();
System.out.println("\r\n-------binarySearchTest-------");
binarySearchTest();
System.out.println("\r\n-------hashSearchTest-------");
hashSearchTest();
System.out.println("\r\n-------insertionSortTest-------");
insertionSortTest();
System.out.println("\r\n-------shellSortTest-------");
shellSortTest();
System.out.println("\r\n-------mergeSortTest-------");
mergeSortTest();
}
运行结果:
-------shellSortTest-------
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)
Round 0
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)
Round 1
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)
Round 2
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)