基本排序方法-希尔排序

       希尔排序法是插入排序的扩展,它通过允许非相邻的元素进行交换来提高执行效率.该算法的思想是将文件重新排列,使文件具有这样的性质,每第h个元素(从任何地方开始)产生一个排好序的文件.这样的文件称为h-排序的.换句话说,h-排序的文件是h个独立的已排好序的文件,相互交叉在一起.对h值较大的h-排序文件,可以通过移动相距较远的元素,比较容易地使h值较小时进行h-排序.通过对直到1的h值的序列进行操作,就会产生一个排好序的文件:这就是希尔排序的本质.                                                                             如果在插入排序中,我们不使用观察哨,并且用h代替1,结果就得到h-排序的文件.增加一个外部循环来改变步长就实现了希尔排序方法,这里实现的步长序列是3*h+1(h = 0, 1, 2, ...)

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <stack>
#include <queue>
#include <malloc.h>
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;

void Shellsort(int a[], int l, int r)
{
    int i, h;
    for(h = 1; h <= (r-l)/9; h = h*3+1);
    for( ; h > 0; h /= 3)
    {
        for(i = l+h; i <= r; i++)
        {
            int j = i, temp = a[i];
            while(j >= l+h && temp < a[j-h])
            {
                a[j] = a[j-h];
                j -= h;
            }
            a[j] = temp;
        }
    }

}
//输出函数
void Print(int a[], int l, int r)
{
    int i;
    for(i = l; i <= r; i++)
    {
        printf("%d ", a[i]);
    }
    printf("\n");
}
int main()
{
    int a[7] = {2, 5, 3, 7, 6, 1, 4};
    //插入排序的改进
    Shellsort(a, 0, 6);
    Print(a, 0, 6);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42480264/article/details/81671324
今日推荐