希尔排序的实现

本题要求实现一趟希尔排序函数,待排序列的长度1<=n<=1000。

函数接口定义:

1 void  ShellInsert(SqList L,int dk);

其中L是待排序表,使排序后的数据从小到大排列。
###类型定义:

1 typedef  int  KeyType;
2 typedef  struct {                      
3   KeyType *elem; /*elem[0]一般作哨兵或缓冲区*/                       
4   int Length;      
5 }SqList;

裁判测试程序样例:

#include<stdio.h>
#include<stdlib.h>
typedef  int  KeyType;
typedef  struct {                      
  KeyType *elem; /*elem[0]一般作哨兵或缓冲区*/                       
  int Length;      
}SqList;
void  CreatSqList(SqList *L);/*待排序列建立,由裁判实现,细节不表*/ 
void  ShellInsert(SqList L,int dk);
void  ShellSort(SqList L);

int main()
{
  SqList L;
  int i;
  CreatSqList(&L);
  ShellSort(L);
  for(i=1;i<=L.Length;i++)
   {        
     printf("%d ",L.elem[i]);
   }
  return 0;
}
void   ShellSort(SqList L)
{
  /*按增量序列dlta[0…t-1]对顺序表L作Shell排序,假设规定增量序列为5,3,1*/
   int k;
   int dlta[3]={5,3,1};
   int t=3;
   for(k=0;k<t;++k)
       ShellInsert(L,dlta[k]);
} 
/*你的代码将被嵌在这里 */

代码如下:

void  ShellInsert(SqList L,int dk){
    for(int i=dk+1;i<=L.Length;i++){
        int p=i;
        L.elem[0]=L.elem[p];
        p-=dk;
        while(p>0&&L.elem[p]>L.elem[0]){
            L.elem[p+dk]=L.elem[p];
            p-=dk;
        }
        L.elem[p+dk]=L.elem[0];  
    }
}

 

posted @ 2022-12-23 21:08  庞司令  阅读(57)  评论(0)    收藏  举报