Advertisement
bkit4s0

[counting sort]ban loi

Dec 22nd, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define MAX 10
  4. #define in "in.txt"
  5. #define out "out.txt"
  6. void insertionsort(int a[], int n)
  7. {
  8.         int i,j,key;
  9.         for (int j = 1; j < n; ++j)
  10.         {
  11.                 key = a[j];
  12.                 i = j -1;
  13.                 while(i>=0&&a[i]>key)
  14.                 {
  15.                         a[i+1] = a[i];
  16.                         i = i-1;
  17.                 }
  18.                 a[i+1] = key;
  19.         }
  20. }
  21. void countingsort(int a[],int b[], int k)
  22. {
  23.     int c[MAX];
  24.     for (int i = 0; i < k; ++i)
  25.     {
  26.         c[i] =0;
  27.     }
  28.     for (int i = 0; i < MAX; ++i)
  29.     {
  30.         c[a[i]] = c[a[i]] + 1;
  31.     }
  32.     for (int i = 0; i < k; ++i)
  33.     {
  34.         c[i]= c[i] + c[i-1];
  35.     }
  36.     for (int i = MAX-1; i >= 0; --i)
  37.     {
  38.         b[c[a[i]]] = a[i];
  39.         c[a[i]] = c[a[i]] -1;
  40.     }
  41. }
  42. void GhiFileSoNguyen(int n)
  43. {
  44.     FILE *f;
  45.     f = fopen(in,"wt");
  46.     if(f==NULL)
  47.     {
  48.         printf("Khong tao duoc file\n");
  49.         //getch();
  50.         exit(0);
  51.     }
  52.     for (int i = 0; i < n; ++i)
  53.     {
  54.         fprintf(f, "%d\n", rand()%MAX);
  55.     }
  56.     fprintf(f, "\n" );
  57.     fclose(f);
  58. }
  59. void GhiFile(int a[MAX], int n)
  60. {
  61.     FILE *f;
  62.     f = fopen(out,"wt");
  63.     if(f==NULL)
  64.     {
  65.         printf("Khong tao duoc file\n");
  66.         //getch();
  67.         exit(0);
  68.     }
  69.     for (int i = 0; i < n; ++i)
  70.     {
  71.         fprintf(f, "%d\n", a[i]);  
  72.     }
  73.     fprintf(f, "\n" );
  74.     fclose(f);
  75. }
  76. void DocFile(int a[MAX], int n)
  77. {
  78.     FILE *f;
  79.     f = fopen(in,"rt");
  80.     if(f==NULL)
  81.     {
  82.         printf("Khong doc duoc file\n");
  83.         //getch();
  84.         exit(0);
  85.     }
  86.     for (int i = 0; i < n; ++i)
  87.     {
  88.         fscanf(f, "%d\l", &a[i]);
  89.     }
  90.     fclose(f);
  91. }
  92. int main(int argc, char const *argv[])
  93. {
  94.     int a[MAX], b[MAX];
  95.     GhiFileSoNguyen(MAX);
  96.     DocFile(a,MAX);
  97.     countingsort(a,b,MAX);
  98.     GhiFile(a,MAX);
  99.     for(int i=0; i<MAX; i++)
  100.         printf("%d\n",a[i]);
  101.     system("pause");
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement