点击(此处)折叠或打开
- #include<stdio.h>
- typedef struct
- {
- int key;
- }keytype;
- typedef struct
- { keytype r[100];
- int length;
- }sqlist;
- /*创建顺序表*/
- void creat(sqlist *l)
- {
- int i,key;
- printf("please intput it's length:");
- scanf("%d",&l->length);
- printf("\n\nplease intput %d data\n",l->length);
- for(i=1;i<=l->length;i++)
- {
- scanf("%d",&key);
- l->r[i].key=key;
- }
- }
- /*显示顺序表*/
- void display(sqlist *l)
- { int i;
- for(i=1;i<=l->length;i++)
- printf("%-4.2d",i);
- printf("\n");
- for(i=1;i<=2*l->length;i++)
- printf("--");
- printf("\n");
- for(i=1;i<=l->length;i++)
- printf("%-4.2d",l->r[i].key);
- }
- /*调整h->r[s]的关键字,使h->r[s]成为一个大顶堆*/
- void heapadjust(sqlist *h,int s,int m)
- { keytype rc;
- int j;
- rc=h->r[s];
- for(j=2*s;j<=m;j*=2)
- { if(j<m&&h->r[j].key<h->r[j+1].key)
- ++j;
- if(rc.key>=h->r[j].key) break;
- h->r[s]=h->r[j];
- s=j;
- }
- h->r[s]=rc;
- }
- /*对顺序表h进行堆排序*/
- void heapsort(sqlist *h)
- { keytype rc;int i;
- for(i=h->length/2;i>0;--i)
- heapadjust(h,i,h->length);
- for(i=h->length;i>1;--i)
- { rc=h->r[1];
- h->r[1]=h->r[i];
- h->r[i]=rc;
- heapadjust(h,1,i-1);
- }
- }
- /*主函数*/
- void main()
- { sqlist t;int i;
- creat(&t);
- printf("\n\n");
- heapsort(&t);
- printf("\n");
- printf("\nheapsort means:\n");
- display(&t);
- getch();
- }
点击(此处)折叠或打开
- #include<stdio.h>
- typedef struct
- {
- int key;
- }keytype;
- typedef struct
- { keytype r[100];
- int length;
- }sqlist;
- /*创建顺序表*/
- void creat(sqlist *l)
- {
- int i,key;
- printf("please intput it's length:");
- scanf("%d",&l->length);
- printf("\n\nplease intput %d data\n",l->length);
- for(i=1;i<=l->length;i++)
- {
- scanf("%d",&key);
- l->r[i].key=key;
- }
- }
- /*交换顺序表中子表r[low...high]的记录,使枢轴记录到位,并返回其所在的位置*/
- int partion(sqlist *l,int low,int high)
- { int pivotkey;
- l->r[0]=l->r[low];
- pivotkey=l->r[low].key;
- while(low<high)
- { while(low<high&&l->r[high].key>=pivotkey)
- --high;
- l->r[low]=l->r[high];
- while(low<high&&l->r[low].key<=pivotkey)
- ++low;
- l->r[high]=l->r[low];
- }
- l->r[low]=l->r[0];
- return low;
- }
- /*快速排序*/
- void Qsort(sqlist *l,int low,int high)
- { int pivotloc;
- if(low<high)
- { pivotloc=partion(l,low,high);
- Qsort(l,low,pivotloc-1);
- Qsort(l,pivotloc+1,high);
- }
- }
- /*显示顺序表*/
- void display(sqlist *l)
- { int i;
- for(i=1;i<=l->length;i++)
- printf("%-4.2d",i);
- printf("\n");
- for(i=1;i<=2*l->length;i++)
- printf("--");
- printf("\n");
- for(i=1;i<=l->length;i++)
- printf("%-4.2d",l->r[i].key);
- }
- /*主函数*/
- void main()
- { sqlist t;int i;
- creat(&t);
- Qsort(&t,1,t.length);
- printf("\n\n");
- printf("quicksort means:\n");
- display(&t);
- getch();
- }
相关热门文章