loulett

HW1_bubble

Oct 27th, 2014
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <assert.h>
  5.  
  6.  
  7. int * std_in(int* n)
  8. {
  9.     scanf("%d", n);
  10.     int * arr = (int *)malloc((*n) * sizeof(int));
  11.     for (int i = 0; i < *n; ++i)
  12.     {
  13.         scanf("%d", &arr[i]);
  14.     }
  15.     return arr;
  16. }
  17.  
  18. int * file_in(int* n)
  19. {
  20.     FILE *file = fopen("bubble_in.txt", "r");
  21.     assert(file);
  22.     fscanf(file, "%d", n);
  23.     int * arr = (int *)malloc((*n) * sizeof(int));
  24.     for (int i = 0; i < *n; ++i)
  25.     {
  26.         fscanf(file, "%d", &arr[i]);
  27.     }
  28.     fclose(file);
  29.     return arr;
  30. }
  31.  
  32. int * generate(int* n)
  33. {
  34.     (*n) = rand();
  35.     int * arr = (int *)malloc((*n) * sizeof(int));
  36.     for (int i = 0; i < *n; ++i)
  37.     {
  38.         arr[i] = rand();
  39.     }
  40.     return arr;
  41. }
  42.  
  43. void bubble_sort(int *a, int n)
  44. {
  45.     int t = 0;
  46.     for (int i = 0; i < n; ++i)
  47.     {
  48.         for (int j = 0; j < n - i - 1; ++j)
  49.         {
  50.             if (a[j] > a[j + 1])
  51.             {
  52.                 t = a[j];
  53.                 a[j] = a[j + 1];
  54.                 a[j + 1] = t;
  55.             }
  56.         }
  57.     }
  58. }
  59.  
  60. void std_out(int *n, int *arr)
  61. {
  62.     for (int i = 0; i < *n; ++i)
  63.         printf("%d ", arr[i]);
  64. }
  65.  
  66. void file_out(int *n, int *arr)
  67. {
  68.     FILE *file = fopen("bubble_out.txt", "w");
  69.     assert(file);
  70.     for (int i = 0; i < *n; ++i)
  71.         fprintf(file, "%d ", arr[i]);
  72.     fclose(file);
  73. }
  74.  
  75. int main()
  76. {
  77.     int n = 0;
  78.  
  79.     int* c = generate(&n);
  80.     bubble_sort(c, n);
  81.     std_out(&n, c);
  82.  
  83.     int* a = file_in(&n);
  84.     bubble_sort(a, n);
  85.     file_out(&n, a);
  86.    
  87.     int* b = std_in(&n);
  88.     bubble_sort(b, n);
  89.     std_out(&n, b);
  90.  
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment