希尔排序
1、思想:希尔排序和直接插入排序很相似,希尔排序是在直接插入排序的基础上进行改进,将待排序列按增量d(一般d的初始值为d=array.length/2)分为诺干组,分别在每个组内进行直接插入排序,然后将增量d按照一定的规则减小(一般按照d=d/2的规则减小)。所以,这里我们可以参考以前的一篇文章“常用排序算法之直接插入排序”,希尔排序的代码也是在这篇文章代码之上修改而来的。
2、希尔排序的过程这里引用一下赵坚、姜梅主编的《数据结构(C语言版)》第8章的【例8-3】,这本书是博主上大学时的教材,希尔排序在本书中写的很清晰,所以就引用一下,希望能够帮助大家理解。
3、代码实现(java)
package sort.baohuajie;
import java.util.Arrays;
/**
* @author 包华杰
* 2017年12月3日
*
* 这里使用两种方法实现。本人认为,第二种方法更能体现插入排序的思想。
* 本代码是在直接插入排序的基础上修改而来的,可以参考以前的一篇博客
*/
public class ShellSort {
public static void shellSort1(int[] array) {
int temp;
int d=array.length/2;
int time=0;
while(d>0){
for (int i = d; i < array.length;) {
for (int j = i; j > 0;) {
if (array[j] < array[j - d]) {
temp = array[j - d];
array[j - d] = array[j];
array[j] = temp;
}
j=j-d;
time++;
System.out.println("第" + time + "次排序结果:"+ Arrays.toString(array));
}
i=i+d;
}
d=d/2;
}
}
public static void shellSort2(int[] array) {
int temp=0;
int j=0;
int time=0;
int d=array.length/2;
while(d>0){
for(int i=d;i<array.length;){
temp=array[i];
j=i-d;
while(j>=0 && temp<array[j]){
array[j+d]=array[j];
j=j-d;
}
array[j+d]=temp;
i=i+d;
}
d=d/2;
time++;
System.out.println("第" + time + "次排序结果:"
+ Arrays.toString(array));
}
}
public static void main(String[] args) {
int[] array = { 58,46,71,95,84,25,37,58,63,12 };
shellSort2(array);
}
}
4、执行结果
第1次排序结果:[25, 46, 71, 95, 84, 58, 37, 58, 63, 12]
第2次排序结果:[25, 46, 37, 95, 63, 58, 71, 58, 84, 12]
第3次排序结果:[12, 25, 37, 46, 58, 58, 63, 71, 84, 95]
【上一篇】常用排序算法之折半插入排序
【下一篇】常用排序算法之冒泡排序