小朋友学数据结构(9):希尔排序
(一)基本思想
希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
(二)例子
有一个数组,其原始数组为:
![](http://upload-images.jianshu.io/upload_images/6946981-6d36b509583f302c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/831/format/webp)
2-1.png
取初始增量gap = length / 2 = 5,这样就将整个数组分为5组(每组用相同的颜色表示)
![](http://upload-images.jianshu.io/upload_images/6946981-3fbc48a67af14e83.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/875/format/webp)
2-2.png
将这5组的数据分别按由小到大的顺序排列,结果为
![](http://upload-images.jianshu.io/upload_images/6946981-c435a5e74c91c63d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/859/format/webp)
2-3.png
缩小增量gap = gap / 2 = 2,整个数组被分成两组
![](http://upload-images.jianshu.io/upload_images/6946981-687ac0832f5d3ed8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/845/format/webp)
2-4.png
将这两组的数据分别按由小到大的顺序排列,结果为
![](http://upload-images.jianshu.io/upload_images/6946981-d6b1ea7666a3af15.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/822/format/webp)
2-5.png
再次缩小增量,整个数组被分为1组
![](http://upload-images.jianshu.io/upload_images/6946981-3bed101a709d4a54.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/826/format/webp)
2-6.png
将这组数据按从小到大的顺序排序,最终结果为
![](http://upload-images.jianshu.io/upload_images/6946981-21c9c65cbc895d20.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/826/format/webp)
2-7.png
(三)代码
1 C语言实现
#include<stdio.h>
void swap(int &a, int &b) { a ^= b; b ^= a; a ^= b; } void shellsort(int a[], int n) { int i, j, gap; for (gap = n / 2; gap > 0; gap /= 2) { for (i = gap; i < n; i++) { for (j = i - gap; j >= 0 && a[j] > a[j + gap]; j -= gap) { swap(a[j], a[j + gap]); } } } } int main() { int arr[] = {49, 38, 65, 97, 76, 13, 27, 48, 55, 4}; printf("Original array: "); int i; int len = sizeof(arr)/sizeof(int); for(i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\n"); shellsort(arr, len); printf("Sorted array: "); for(i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
2 Java实现
import java.util.Arrays;
public class Sort { public static void shellSort(int[] a) { int i, j, gap; int len = a.length; for (gap = len / 2; gap > 0; gap /= 2) { for (i = gap; i < len; i++) { for (j = i - gap; j >= 0 && a[j] > a[j + gap]; j -= gap) { // 交换两个数 a[j] ^= a[j + gap]; a[j + gap] ^= a[j]; a[j] ^= a[j + gap]; } } } } public static void main(String[] args) { int[] arr = {49, 38, 65, 97, 76, 13, 27, 48, 55, 4}; System.out.println("Original array: " + Arrays.toString(arr)); shellSort(arr); System.out.println("Sorted array: " + Arrays.toString(arr)); } }
3 运行结果
Original array: [49, 38, 65, 97, 76, 13, 27, 48, 55, 4] Sorted array: [4, 13, 27, 38, 48, 49, 55, 65, 76, 97]
![](https://i-blog.csdnimg.cn/blog_migrate/9129b48df94a217714f433f9dab54e9a.png)