算法基础之希尔排序

希尔排序的实质就是分组插入排序, 是对直接插入排序的改进。 时间复杂度为O(nlongn), 跟快速排序, 堆排序的时间复杂度相同, 是一种较为快速的排序方式。

该方法的基本思想是:先将整个待排元素序列分割成若干个子序列(由相隔某个“增量”的 元素组成的)分别进行直接插入排序,然后依次缩减增量再进行排序,待整个序列中的元素基本有序(增量足够小)时,再对全体元素进行一次直接插入排序。因为 直接插入排序在元素基本有序的情况下(接近最好情况),效率是很高的,因此希尔排序在时间效率上比前两种方法有较大提高。

希尔排序的C语言实现如下:

 1 void Swap(int a[], int j, int gap) 
 2 {
 3     int temp = a[j];
 4     a[j] = a[j+gap];
 5     a[j+gap] = temp;
 6 }
 7 
 8 /* 希尔排序算法的C语言实现 */
 9 
10 void shell_sort(int a[], int n)
11 {
12        int i, j, gap;
13        for (gap = n / 2; gap > 0; gap /= 2)
14        {
15             for (i = gap; i < n; i++)
16             {
17                 for (j = i - gap; j >= 0 && a[j] > a[j + gap]; j -= gap)
18                 {
19                     Swap(a, j, gap);
20                 }
21             }
22        }
23 }

一个简单的测试用例,代码如下:

#include<stdio.h>

#define MAXSIZE 10

void Swap(int a[], int j, int gap) 
{
    int temp = a[j];
    a[j] = a[j+gap];
    a[j+gap] = temp;
}

/* 希尔排序算法的C语言实现 */

void shell_sort(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, gap);
                }
            }
       }
}



int main()
{
    int a[MAXSIZE];
    int i;
    printf("Please input the num:
");
    for(i=0; i<MAXSIZE; i++)
    {
        scanf("%d",&a[i]);
    }
    printf("before the sort:
");
    for(i=0; i<MAXSIZE; i++)
    {
        printf("%d ", a[i]);
    }
    printf("
");
    
    shell_sort(a, MAXSIZE);

    printf("after the sort:
");
    for(i=0; i<MAXSIZE; i++)
    {
        printf("%d ", a[i]);
    }
    printf("
");
}
View Code
原文地址:https://www.cnblogs.com/beyond-Acm/p/4354761.html