第十六周 项目3-归并排序算法的改进
来源:互联网 发布:南京行知中学地址 编辑:程序博客网 时间:2024/06/04 23:35
问题及代码:
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #include <time.h>
- #define MinLength 64 //最短分段长度
- typedef int KeyType;
- typedef char InfoType[10];
- typedef struct
- {
- KeyType key;
- InfoType data;
- } RecType;
-
- void GetData(RecType *&R, int n)
- {
- srand(time(0));
- R=(RecType*)malloc(sizeof(RecType)*n);
- for(int i=0; i<n; i++)
- R[i].key= rand();
- printf("生成了%d条记录\n", n);
- }
-
-
- void InsertSort(RecType R[],int low,int high)
- {
- int i,j;
- RecType tmp;
- for (i=low; i<=high; i++)
- {
- tmp=R[i];
- j=i-1;
- while (j>=low && tmp.key<R[j].key)
- {
- R[j+1]=R[j];
- j--;
- }
- R[j+1]=tmp;
- }
- }
-
-
- void Merge(RecType R[],int low,int mid,int high)
- {
- RecType *R1;
- int i,j,k;
- i=low,j=mid+1,k=0;
- R1=(RecType *)malloc((high-low+1)*sizeof(RecType));
- while (i<=mid && j<=high)
- if (R[i].key<=R[j].key)
- {
- R1[k]=R[i];
- i++;
- k++;
- }
- else
- {
- R1[k]=R[j];
- j++;
- k++;
- }
- while (i<=mid)
- {
- R1[k]=R[i];
- i++;
- k++;
- }
- while (j<=high)
- {
- R1[k]=R[j];
- j++;
- k++;
- }
- for (k=0,i=low; i<=high; k++,i++)
- R[i]=R1[k];
- }
-
-
- void MergePass(RecType R[],int length,int n)
- {
- int i;
- for (i=0; i+2*length-1<n; i=i+2*length)
- Merge(R,i,i+length-1,i+2*length-1);
- if (i+length-1<n)
- Merge(R,i,i+length-1,n-1);
- }
-
-
- void MergeSort(RecType R[],int n)
- {
- int length, i;
- for(i=0;i<n;i+=MinLength)
- InsertSort(R, i, ((i+MinLength-1<n)?(i+MinLength-1):n));
- for (length=MinLength; length<n; length=2*length)
- {
- MergePass(R,length,n);
- }
- }
-
- int main()
- {
- int i,n=10000;
- RecType *R;
- GetData(R, n);
- MergeSort(R,n);
- printf("排序后(前300个):\n");
- i=0;
- while(i<300)
- {
- printf("%12d ",R[i].key);
- i++;
- if(i%5==0)
- printf("\n");
- }
- printf("\n");
- printf("排序后(后300个):\n");
- i=0;
- while(i<300)
- {
- printf("%12d ",R[n-300+i].key);
- i++;
- if(i%5==0)
- printf("\n");
- }
- printf("\n");
- free(R);
- return 0;
- }
运行结果
0 0