peterzig

[AISD] Sortowanie z pliku bubble

Apr 24th, 2016
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. // ConsoleApplication1.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <conio.h>
  6. #include <malloc.h>
  7.  
  8. FILE *plik;
  9.  
  10. bool Test(const float * const tab, const int n)
  11. {
  12.     if (tab == 0) return false;
  13.     if (n <= 0) return false;
  14.     if (n > 100000) return false;
  15.     for (int i = 0; i < n - 1; ++i)
  16.     {
  17.         if (tab[i] > tab[i + 1]) return false;
  18.     }
  19.     return true;
  20. }
  21.  
  22. float* WczytajDane(const char *fileName, int *n)
  23. {
  24.     if ((plik = fopen(fileName, "r")) == NULL)
  25.     {
  26.         printf("Blad otwarcia pliku %s!", fileName);
  27.         return false;
  28.     }
  29.     fscanf(plik, "%d", n);
  30.     float *tab = (float*)malloc(sizeof(float)*(*n));
  31.    
  32.     for (int i = 0; i < (*n); i++)
  33.     {
  34.         fscanf(plik, "%f", tab[i]);
  35.     }
  36.     return tab;
  37. }
  38.  
  39. void SortujBabelkowo(float *Dane, const int n)
  40. {
  41.     float x;
  42.     for (int i = 0; i < n - 1; i++)
  43.     {
  44.         for (int j = 0; j < n - 1; j++)
  45.         {
  46.             if (Dane[j] > Dane[j + 1])
  47.             {
  48.                 x = Dane[j + 1];
  49.                 Dane[j + 1] = Dane[j];
  50.                 Dane[j] = x;
  51.             }
  52.         }
  53.     }
  54. }
  55.  
  56. void SortujPrzezWybieranie(float *Dane, const int n)
  57. {
  58.     int k;
  59.     float x;
  60.     for (int i = 0; i < n; i++)
  61.     {
  62.         k = i;
  63.         for (int j = i + 1; j < n; j++)
  64.         {
  65.             if (Dane[j] < Dane[k]) k = j;
  66.         }
  67.         x = Dane[k];
  68.         Dane[k] = Dane[i];
  69.         Dane[i] = x;
  70.     }
  71. }
  72.  
  73. int main()
  74. {
  75.     int n;
  76.  
  77.     float *tab = WczytajDane("sortowanie.txt", &n);
  78.     printf("Liczba danych: %d\n", n);
  79.     SortujBabelkowo(tab, n);
  80.     printf("Metoda sortowania babelkowego\n");
  81.     if (Test(tab, n)) printf("Dane posortowane prawidlowo\n"); else printf("Dane posortowane nieprawidlowo\n");
  82.     SortujPrzezWybieranie(tab, n);
  83.     printf("Metoda sortowania przez wybieranie.\n");
  84.     if (Test(tab, n)) printf("Dane posortowane prawidlowo\n"); else printf("Dane posortowane nieprawidlowo\n");
  85.     free(tab);
  86.     _getch();
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment