冒泡排序与归并排序运行时间的比较

为了证明自己的正确性,特写此文章,真理从来都是实践得到的。。。

 

https://github.com/congmingyige/Something-in-algorithm-lesson

 

生成数据:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 
 5 int main()
 6 {
 7     FILE *fp=fopen("sort.in","w");
 8     long n,i;
 9     srand(time(NULL));//wrong
10     scanf("%ld",&n);
11     fprintf(fp,"%ld\n",n);
12     for (i=1;i<=n;i++)
13         fprintf(fp,"%ld ",rand()*9+rand());
14     fclose(fp);
15     return 0;
16 }

 

冒泡排序:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 long a[100005];
 4 
 5 int main()
 6 {
 7     FILE *fp1=fopen("sort.in","r");
 8     FILE *fp2=fopen("sort.out","w");
 9     long n,i,j,k,t;
10 //    scanf("%ld",&n);
11 //    for (i=1;i<=n;i++)
12 //        scanf("%ld",&a[i]);
13     fscanf(fp1,"%ld",&n);
14     for (i=1;i<=n;i++)
15         fscanf(fp1,"%ld",&a[i]);
16     //bubble sort
17     for (i=1;i<n;i++)
18         for (j=n,k=n-1;j>i;j--,k--)
19             if (a[j]<a[k])
20             {
21                 t=a[j];
22                 a[j]=a[k];
23                 a[k]=t;
24             }
25 //    for (i=1;i<=n;i++)
26 //        printf("%ld ",a[i]);
27     for (i=1;i<=n;i++)
28         fprintf(fp2,"%ld ",a[i]);
29     fclose(fp1);
30     fclose(fp2);
31     return 0;
32 }

 

归并排序:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 long a[100005],b[100005];
 4 
 5 void mergesort(long l,long r)
 6 {
 7     long mid=(l+r)>>1,i,j,k;
 8     if (l!=mid)
 9         mergesort(l,mid);
10     if (mid<r)
11         mergesort(mid+1,r);
12     for (i=l;i<=r;i++)
13         b[i]=a[i];
14     i=l; j=mid+1; k=l;
15     while (i<=mid && j<=r)
16     {
17         if (b[i]<b[j])
18         {
19             a[k]=b[i];
20             k++;
21             i++;
22         }
23         else if (b[i]>b[j])
24         {
25             a[k]=b[j];
26             k++;
27             j++;
28         }
29         else
30         {
31             a[k]=b[i];
32             k++;
33             i++;
34             a[k]=b[j];
35             k++;
36             j++;
37         }
38     }
39     while (i<=mid)
40     {
41         a[k]=b[i];
42         k++;
43         i++;
44     }
45     while (j<=r)
46     {
47         a[k]=b[j];
48         k++;
49         j++;
50     }
51 }
52 
53 int main()
54 {
55     FILE *fp1=fopen("sort.in","r");
56     FILE *fp2=fopen("sort.out","w");
57     long n,i;
58 //    scanf("%ld",&n);
59 //    for (i=1;i<=n;i++)
60 //        scanf("%ld",&a[i]);
61     fscanf(fp1,"%ld",&n);
62     for (i=1;i<=n;i++)
63         fscanf(fp1,"%ld",&a[i]);
64     //mergesort
65     mergesort(1,n);
66 //    for (i=1;i<=n;i++)
67 //        printf("%ld ",a[i]);
68     for (i=1;i<=n;i++)
69         fprintf(fp2,"%ld ",a[i]);
70     fclose(fp1);
71     fclose(fp2);
72     return 0;
73 }

 

 

 

 

 

posted @ 2018-05-09 20:14  congmingyige  阅读(856)  评论(0编辑  收藏  举报