1.希尔排序
该排序方法的基本思想是:先将整个待排元素序列分割成若干个子序列(由相隔某个“增量”的元素组成的)分别进行直接插入排序,然后依次缩减增量再进行排序,待整个序列中的元素基本有序(增量足够小)时,再对全体元素进行一次直接插入排序。因为直接插入排序在元素基本有序的情况下(接近最好情况),效率是很高的。
下面这张图一看就知道希尔排序思想是怎样的了吧。
2.代码
/**
*
***********************************
* @Title: shellSort
* @Description: Shell sort
* @param:
* @return: void
***********************************
*/
public void shellSort() {
DataNode tempNode;
int[] tempJumpArray = { 4, 2, 1 };
int tempJump;
int p;
for (int i = 0; i < tempJumpArray.length; i++) {
//不同步进
tempJump = tempJumpArray[i];
for (int j = 0; j < tempJump; j++) {// 从0到尾
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) {
// data[p].key为前面的元素的值,tempNode为间隔后面的元素的值
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
/**
*
***********************************
* @Title: shellSortTest
* @Description: Test the method.
* @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);
}// Of shellSortTest
/**
*
***********************************
* @Title: main
* @Description:
* @param: @param args
* @return: void
***********************************
*/
public static void main(String args[]) {
System.out.println("\r\n-------shellSortTest-------");
shellSortTest();
}// Of main
3.总结
在希尔排序中,最好情况是步长为1的时候,并且整个序列几乎是有序的情况,这时时间复杂度为O(n)。在上面程序中,时间复杂度为。而希尔排序的时间复杂度是与步长序列有关的。