`
lilisalo
  • 浏览: 1102302 次
文章分类
社区版块
存档分类
最新评论

希尔排序及C语言实现

 
阅读更多

排序系列之(4)希尔排序及C语言实现 收藏
希尔排序(Shell Sort)也称为递减增量排序算法,是插入排序的一种高速而安定的改良版。因希尔(Donald L. Shell)于1959年提出而得名。各种实现在如何进行递减上有所不同。

希尔排序是基于插入排序的以下两点性质而提出改进方法的:
插入排序在对几乎已经排好序的数据操作时, 效率高, 即可以达到线性排序的效率
但插入排序一般来说是低效的, 因为插入排序每次只能将数据移动一位

以下是其C语言实现
view plaincopy to clipboardprint?
#include "shellSort.h"
#include "common.h"
void shellSort(int a[],int len)
{
int step;
int i,j;
int temp;
for(step=len/2; step>0;step/=2) //用来控制步长,最后递减到1
{
// i从第step开始排列,应为插入排序的第一个元素
// 可以先不动,从第二个开始排序
for(i=step;i<len;i++)
{
temp = a[i];
for(j=i-step;(j>=0 && temp < a[j]);j-=step)
{
a[j+step] = a[j];
}
a[j+step] = temp; //将第一个位置填上
}
showArray(a,len);
}
}
void shellSortTest()
{
int a[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200};
int len = sizeof(a)/sizeof(int);
printf("Init.../n");
showArray(a,len);
printf("Begin sorting.../n");
shellSort(a,len);
printf("After sorting.../n");
showArray(a,len);
}
#include "shellSort.h"
#include "common.h"
void shellSort(int a[],int len)
{
int step;
int i,j;
int temp;
for(step=len/2; step>0;step/=2) //用来控制步长,最后递减到1
{
// i从第step开始排列,应为插入排序的第一个元素
// 可以先不动,从第二个开始排序
for(i=step;i<len;i++)
{
temp = a[i];
for(j=i-step;(j>=0 && temp < a[j]);j-=step)
{
a[j+step] = a[j];
}
a[j+step] = temp; //将第一个位置填上
}
showArray(a,len);
}
}
void shellSortTest()
{
int a[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200};
int len = sizeof(a)/sizeof(int);
printf("Init.../n");
showArray(a,len);
printf("Begin sorting.../n");
shellSort(a,len);
printf("After sorting.../n");
showArray(a,len);
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/taizhoufox/archive/2010/10/22/5959437.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics