一、介绍:
希尔排序是一种可以减少插入排序中数据比较次数的排序算法,加速算法的进行,排序的原则是将数据区分为特定步长的小区块,然后以插入排序算法对小区块内部进行排序,经历过一轮排序则减少步长,直到所有数据都排序完成。
演示:
首先步长step的值是用待查找的数据长度决定的,初始值为step = 待查找数据的长度/2

视频演示:
- void ShellSort(int[] data)
- {
- int step = data.Length / 2;
- int preIdx , current = 0;
- while (step > 0)
- {
- for (int i = step; i < data.Length; i++)
- {
- preIdx = i - step;
- current = data[i];
-
- while (preIdx >= 0 && data[preIdx] > current)
- {
- data[preIdx + step] = data[preIdx];
- preIdx -= step;
- }
- data[preIdx + step] = current;
- }
- step = step / 2;
- }
- }
- void ShellSort2(int[] data)
- {
- int step = data.Length / 2;
- int preIdx, current = 0;
- while (step > 0)
- {
- for (int i = 0; i < data.Length - step; i +=step)
- {
- preIdx = i;
- current = data[i + step];
-
- while (preIdx >= 0 && data[preIdx] > current)
- {
- data[preIdx + step] = data[preIdx];
- preIdx -= step;
- }
- data[preIdx + step] = current;
- }
- step = step / 2;
- }
- }