Advertisement
Guest User

Untitled

a guest
May 6th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // finding the index of the biggest number;
  4. int index_of_max(float a[ ], int n)
  5. {
  6.    int i, i_max = 0;
  7.    
  8.    for (i = 1; i < n; i++)
  9.    {
  10.        if (a[i] > a[i_max])
  11.        {
  12.           i_max = i;
  13.        }
  14.    }
  15.    
  16.    return i_max;
  17. }
  18.  
  19. // swapping position of the current biggest number, by pointers;
  20. void swap(float *p1, float *p2)
  21. {
  22.      float p3 = *p1;
  23.      *p1 = *p2;
  24.      *p2 = p3;
  25. }
  26.  
  27. // calculates the final and future location of the current biggest number;
  28. void max_sort(float a[], int n)
  29. {
  30.    int length;
  31.    
  32.    for (length = n ; length > 1; length--)
  33.    {
  34.        int i_max = index_of_max(a, length);
  35.        swap(&a[length-1], &a[i_max]);
  36.    }
  37.    
  38. }
  39.  
  40. // main function;
  41. int main()
  42. {
  43.     FILE *fin;
  44.     int num, i;
  45.     float fnum[num-1];
  46.     fin = fopen("read_it.txt", "rt");
  47.    
  48.     fflush(stdin);
  49.     fscanf(fin, "%d", &num);
  50.    
  51.     // reading the numbers from a file;
  52.     for (i = 0; i < num; i++)
  53.     {
  54.         fflush(stdin);
  55.         fscanf(fin, "%f", &fnum[i]);
  56.         printf("%d. %.2lf\n", i+1, fnum[i]);    
  57.     }
  58.    
  59.     // calling for the function, which will sort the received numbers;
  60.     max_sort(fnum, num);
  61.     putchar('\n');
  62.    
  63.     // reading the numbers on the screen, after they have been sorted;
  64.     for (i = 0; i < num; i++)
  65.     {
  66.         printf("%d. %.2lf\n", i+1, fnum[i]);    
  67.     }
  68.    
  69.     fclose(fin);
  70.     fflush(stdin);
  71.     getchar();
  72.    
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement