Advertisement
Guest User

Untitled

a guest
Oct 21st, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. /*
  2. * Mateusz Soroka grupa 5
  3. * nr indeksu 250999
  4. * Algorytmy i struktury danych
  5. * HeapSort
  6. * Dane zostają wczytane z pliku "unsorted.txt"
  7. * Wynik zostaje zapisany do pliku "sorted.txt"
  8. */
  9.  
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <stdbool.h>
  14.  
  15. void Swap(int *a, int *b){
  16. int temp = *a;
  17. *a = *b;
  18. *b = temp;
  19. }
  20.  
  21. void Heapify(int Array[], int i, int HeapSize){
  22.  
  23. while(true){
  24.  
  25. int Largest = 0;
  26. int LeftSon = 2 * i;
  27. int RightSon = 2 * i + 1;
  28.  
  29. if( LeftSon <= HeapSize && Array[LeftSon-1] > Array[i-1] ) Largest = LeftSon;
  30. else Largest = i;
  31. if( RightSon <= HeapSize && Array[RightSon-1] > Array[Largest-1]) Largest = RightSon;
  32. if( Largest != i){
  33. Swap( &Array[i-1], &Array[Largest-1]);
  34. i = Largest;
  35. }
  36. else break;
  37. }
  38. }
  39.  
  40. void BuildHeap(int Array[], int HeapSize){
  41.  
  42. int i;
  43. for( i=HeapSize/2; i>0; i--) Heapify(Array, i, HeapSize);
  44. }
  45.  
  46. void HeapSort(int Array[], int HeapSize){
  47.  
  48. int i;
  49. BuildHeap(Array, HeapSize);
  50. for( i=HeapSize; i>1; i--){
  51. Swap( &Array[i-1], &Array[0]);
  52. HeapSize--;
  53. Heapify( Array, 1, HeapSize);
  54. }
  55. }
  56.  
  57.  
  58. int main(void){
  59.  
  60. int i;
  61. int HeapSize = 0;
  62.  
  63. FILE *before = fopen("unsorted.txt", "r");
  64. if( before == NULL){
  65. printf("Błąd odczytu pliku lub plik nie istnieje..\n");
  66. exit(0);
  67. }
  68. else{
  69. char ch;
  70. while( ch!= EOF ){
  71. ch = fgetc( before );
  72. if( ch == '\n' ) HeapSize++;
  73. }
  74. printf("Pomyślne otworzenie pliku, rozpoczynanie sortowania..\n");
  75. }
  76.  
  77. int Array[HeapSize];
  78.  
  79. for( i=0; i<HeapSize; i++){
  80. fscanf( before, "%d", &Array[i]);
  81. }
  82.  
  83. fclose( before );
  84.  
  85. HeapSort( Array, HeapSize );
  86.  
  87.  
  88. for(i=0;i<HeapSize;i++){
  89. printf("%d\n",Array[i]);
  90. }
  91.  
  92. /*FILE *after = fopen("sorted.txt","w");
  93. for( i = 0; i<HeapSize; i++){
  94. fprintf( after, "%d\n", Array[i]);
  95. }
  96.  
  97.  
  98. if( after == NULL){
  99. printf("Sortowanie niepomyślne lub błąd pliku wyjściowego..\n");
  100. exit(0);
  101. }
  102. else printf("Sortowanie pomyślne, dane zapisane w 'sorted.txt'..\n");
  103.  
  104. fclose( after );*/
  105.  
  106. return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement