1. 插入排序存在的问题
- 先看以下简单的插入排序可能存在的问题
- 数组 arr = {2,3,4,5,6,1} 这时需要插入的数 1(最小),这样的过程是:
{2,3,4,5,6,6}
{2,3,4,5,5,6}
{2,3,4,4,5,6}
{2,3,3,4,5,6}
{2,2,3,4,5,6}
{1,2,3,4,5,6} - 结论: 当需要插入的数是较小的数时,后移的次数明显增多,对效率有影响
2. 希尔排序介绍
- 希尔排序是希尔(Donald Shell)于1959年提出的一种排序算法。希尔排序也是一种插入排序,它是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序。
3. 基本思想
- 希尔排序是把数据按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止
4. 示意图
![请添加图片描述](https://i-blog.csdnimg.cn/blog_migrate/b335128e13839e6d676b5a0f9336ca61.png)
5. 代码实现
import java.util.Arrays;
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
System.out.println("排序前" + Arrays.toString(arr));
analysisProcess(arr);
int[] arr2 = {7, 6, 5, 4, 3, 2, 1, 8, 9, 0};
System.out.println("排序前" + Arrays.toString(arr2));
shellSort(arr2);
System.out.println("排序后" + Arrays.toString(arr2));
}
public static void analysisProcess(int[] arr) {
int insertVal = 0;
int insertIndex = 0;
for (int i = 5; i < arr.length; i++) {
insertVal = arr[i];
insertIndex = i - 5;
while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
arr[insertIndex + 5] = arr[insertIndex];
insertIndex -= 5;
}
if (insertIndex + 5 != i) {
arr[insertIndex + 5] = insertVal;
}
}
System.out.println("第1轮后" + Arrays.toString(arr));
for (int i = 2; i < arr.length; i++) {
insertVal = arr[i];
insertIndex = i - 2;
while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
arr[insertIndex + 2] = arr[insertIndex];
insertIndex -= 2;
}
if (insertIndex + 2 != i) {
arr[insertIndex + 2] = insertVal;
}
}
System.out.println("第2轮后" + Arrays.toString(arr));
for (int i = 1; i < arr.length; i++) {
insertVal = arr[i];
insertIndex = i - 1;
while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex -= 1;
}
if (insertIndex + 1 != i) {
arr[insertIndex + 1] = insertVal;
}
}
System.out.println("第3轮后" + Arrays.toString(arr));
}
public static void shellSort(int[] arr) {
int insertVal = 0;
int insertIndex = 0;
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < arr.length; i++) {
insertVal = arr[i];
insertIndex = i - gap;
while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
arr[insertIndex + gap] = arr[insertIndex];
insertIndex -= gap;
}
if (insertIndex + gap != i) {
arr[insertIndex + gap] = insertVal;
}
}
}
}
}
排序前[8, 9, 1, 7, 2, 3, 5, 4, 6, 0]
第1轮后[3, 5, 1, 6, 0, 8, 9, 4, 7, 2]
第2轮后[0, 2, 1, 4, 3, 5, 7, 6, 9, 8]
第3轮后[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
排序前[7, 6, 5, 4, 3, 2, 1, 8, 9, 0]
排序后[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]