快速排序和希尔排序

来源:互联网 发布:工业设计作图软件 编辑:程序博客网 时间:2024/06/08 06:46

//////////////////希尔排序和快速排序/////////////
#include<stdio.h>
#define M 100
typedef int KeyType;
typedef struct{
     KeyType key;
}DataType;
typedef struct{
     DataType r[M+1];
     int length;
}SqList;
void ShellInsert(SqList *S,int gap)       /*一趟希尔排序*/
{
 int i,j;
 for(i=gap+1;i<=S->length;i++)
   if(S->r[i].key<S->r[i-gap].key)
   {
      S->r[0]=S->r[i];
      for(j=i-gap;j>0&&S->r[0].key<S->r[j].key;j=j-gap)
          S->r[j+gap]=S->r[j];
          S->r[j+gap]=S->r[0];
   }
}
void ShellSort(SqList *S,int  gaps[],int t)             /*希尔排序*/
{
{
 int  k;
 for(k=0;k<t;k++)
    ShellInsert(S,gaps[k]);
}


int quickSort1(SqList *S,int low,int higt)       /*一趟快速排序*/
 {
   KeyType pivotkey;
   S->r[0]=S->r[low];
   pivotkey=S->r[low].key;
  while(low<higt)
   {
      while(low<higt&&S->r[higt].key>=pivotkey)
    higt--;
    S->r[low]=S->r[higt];
    while(low<higt&&S->r[low].key<=pivotkey)
    low++;
    S->r[higt]=S->r[low];
    }
    S->r[low]=S->r[0];
    return low;
 }
void quickSort(SqList *s,int low,int high)       /*递归形式的快速排序*/*/
{
   KeyType pivotkey;
   if(low<high)
   {
     pivotkey=quickSort1(s,low,high);
     quickSort(s,low,pivotkey-1);
     quickSort(s,pivotkey+1,high);
   }
}

main()
{
 int a[10];
 int t,i,low,high;
 SqList *S,*T;
 low=0;
 printf("/nplease input the length of s:/n");
 scanf("%d",&(S->length));
 printf("/nplease input the elem of s:/n");
 for(i=1;i<=S->length;i++)
  {
    scanf("%d",&S->r[i].key);
  }
 printf("please input length of gap:/n");
 scanf("%d",&t);
 printf("please input the elem of gap/n");
 for(i=0;i<t;i++)
  {
    scanf("%d",&a[i]);
  }
 ShellSort(S,a,t);
 printf("the result after shellsort is:");
 for(i=1;i<=S->length;i++)
  {
    printf("%d ",S->r[i].key);
  }

 printf("/nplease input the length of T:/n");
 scanf("%d",&(T->length));
 printf("/nplease input the elem of T:/n");
 for(i=1;i<=T->length;i++)
  {
    scanf("%d",&T->r[i].key);
  }

 high=T->length;
 quickSort(T,low,high);
 printf("/nthe result after quicksort is:");
 for(i=1;i<=T->length;i++)
  {
    printf("%d ",T->r[i].key);
  }
  getch();
}