代码来自闵老师”日撸 Java 三百行(41-50天)“,链接:https://blog.csdn.net/minfanphd/article/details/116975863
/**
* *****************************************************************
* Shell sort. We do not use sentries here because too many of them are needed.
* *****************************************************************
*/
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 < data.length; k += tempJump) {
tempNode = data[k];
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
data[p + tempJump] = tempNode;
}//of for k
}//of for j
}//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
便于理解算法,附一张图,图片来自于博文:https://www.jianshu.com/p/d730ae586cf3
1、最不好理解的地方是data[p + tempJump] = data[p]和data[p + tempJump] = tempNode;第一句是将大的值往后移位置,每次移动的位置为tempjump。而只有if条件不成立的时候p的for循环会跳出,此时data[p].key是小于tempNode.key的。所以除了p的for循环,tempNode应该放在p的下一个加上tempJump的位置。
2、四个for循环,第一个控制循环的轮数;第二个for控制步长,tempJump每一组内的循环;第三个for循环保证每一轮j循环的时候,对比的是每一组的同一个位置的数据,这样就能将对应位置的数设置成一个插入排序;p的循环是为了查找该次循环的(插入排序)组内位置,跳出p的循环后,完成插入。