Advertisement
hubermlima

Heap sort

Mar 22nd, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 5.22 KB | None | 0 0
  1. /*
  2. ALGORITMO MAX HEAP SORT
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <math.h>
  7. /*
  8.   Define tamanho maximo do array de dados
  9. */
  10. #define SIZE 8
  11.  
  12. /* Declaração de funções e procedimentos */
  13. int potencia();         /* Função que calcula a quantidade de nós em cada nível da árvore (2^p), send p o nível atual */
  14. void populateVector();  /* Procedimento que preenche a estrutura de dados com números não sequenciais */
  15. void showVector();      /* Procedimento que mostra na tela o conteúdo da estrutura de dados */
  16. void maxHeapify();      /* Procedimento que ordena a árvore de acordo com as características de uma estrutura HEAP */
  17. void heapSort();        /* Procedimento que percorre a estrutura de dados n vezes, de acordo com o tamanho atual da mesma */
  18. void drawLevel();       /* Procedimento que desenha o nível atual da estrutura Heap */
  19. void positionNode();    /* Procedimento que posiciona o cursor na posição determinada da estrutura Heap */
  20. void showHeapDataStructure(); /* Procedimento que apresenta em forma de árvore a Estrutura Heap do vetor */
  21.  
  22. /* Declaração da variável que cria o vector de dados com o tamanho determinado */
  23. int data[SIZE];
  24. int main(void) {
  25.     populateVector();
  26.     printf("CHAOTIC DATA:\n");
  27.     showVector();
  28.     heapSort();
  29.     return 0;
  30. }
  31.  
  32. void populateVector(){
  33.     /*
  34.       Considera-se a posição inicial do vetor de dados com o indice a 1
  35.     */
  36.     for(int i = 1; i <= SIZE; i ++){
  37.        scanf("%d",&data[i]);
  38.     }
  39. }
  40.  
  41. void maxHeapify(int i, int size){
  42.            int childRight, childLeft, tmp, parent;
  43.            parent = i;
  44.            if (2 * i + 1 <= size)  
  45.              /*
  46.                Pai com os dois filhos
  47.              */
  48.              {
  49.                   childLeft = 2 * i;
  50.                   childRight = 2 * i + 1;
  51.                   if  (data[childLeft] >= data[childRight] &&
  52.                        data[childLeft] > data[i])
  53.                         parent = childLeft;
  54.                   else if (data[childRight] >= data[childLeft] &&
  55.                        data[childRight] > data[i])
  56.                         parent = childRight;
  57.             }
  58.             else if (2 * i <= size)  
  59.                /*
  60.                  Pai somente com o filho da esquerda
  61.                */
  62.             {
  63.                  childLeft= 2 * i;
  64.                  if (data[childLeft] > data[i])
  65.                          parent = childLeft;
  66.                    
  67.             }
  68.          
  69.           if (parent != i )
  70.           {
  71.                /*
  72.                   Primeira fase: Neste momento ocorre a troca (swap) das posições da sub-arvore, sendo o maior
  73.                   assumindo a posição de pai
  74.                */
  75.  
  76.                tmp = data[i];
  77.                data[i] = data[parent];
  78.                data[parent] = tmp;
  79.                maxHeapify(parent, size);
  80.            }
  81. }
  82.  
  83. void heapSort(){
  84.        int size = SIZE;
  85.        int tmp;
  86.        for (; size >=2; size --){
  87.           for(int i = size/2; i >= 1; i--){
  88.               maxHeapify(i, size);
  89.           }
  90.           printf("\nMAX-HEAP DATA STRUCTURE\n");
  91.           showVector();
  92.           printf("\t\t\t\t\t\t\tRaiz\t\t\t\t  Nivel\n");
  93.           showHeapDataStructure(size);
  94.  
  95.           /*
  96.             Segunda fase: Na primeira execução, o maior (raiz da árvore binária) se desloca para a ultima posição
  97.             do vector de dados. Na segunda execução, o maior vai pra penúltima posição, e assim, sucessivamente, até o
  98.             vector se reduzir à duas posições.
  99.           */
  100.  
  101.           tmp = data[size];
  102.           data[size] = data[1];
  103.           data[1] = tmp;
  104.           if (size == 2) {
  105.               printf("\nFULLY ORDINATED DATA \n");
  106.               showVector(); }
  107.       }
  108. }
  109.  
  110. void showVector(){
  111.    for(int i = 1; i <= SIZE; i ++){
  112.         printf("[%d]\t", data[i]);
  113.    }
  114.    printf("\n\n");
  115. }
  116.  
  117. void showHeapDataStructure(int size){
  118.  
  119.    // mostrar arvore binaria
  120.    int p = 0;
  121.    int tabIni = 7;
  122.    int tabAtual = 7;
  123.    int maxInLineNode = potencia(0);
  124.    int inLineNode = 0;
  125.    int maxLevel = (int) log2(size);
  126.    positionNode(tabAtual);
  127.    for(int i = 1; i <= size; i++){
  128.    
  129.       printf("[%d]", data[i]);
  130.       inLineNode ++;
  131.       printf("\t");  
  132.       tabAtual++;
  133.       if (tabAtual == 7){ /* Divisão dos lados da árvore */
  134.          printf("\t");  tabAtual++; }
  135.  
  136.      if (inLineNode == maxInLineNode) {
  137.           inLineNode = 0;
  138.           drawLevel(tabAtual, p);
  139.           p++;
  140.           if (p<=2)  
  141.              tabIni--;
  142.           else
  143.              tabIni -= 2;
  144.           printf("\n");  
  145.           tabAtual = tabIni;
  146.           positionNode(tabAtual);
  147.      }
  148.      if (p == maxLevel)  {// ultimo nivel
  149.              inLineNode = 0;
  150.              maxInLineNode = size - i;}
  151.            //  printf("Size: %d, i: %d", size, i);}
  152.      else
  153.             maxInLineNode = potencia(p);
  154.    }
  155.  
  156. }
  157.  
  158. int potencia(int p){
  159.     int pot = 1;
  160.     for(int i = 0; i < p; i++)
  161.         pot *= 2;
  162.     return pot;
  163. }
  164. void positionNode(int tab) {
  165.     for (int i = 0; i < tab; i++)
  166.             printf("\t");
  167. }
  168.  
  169. void drawLevel(int tab, int p) {
  170.      for(int i = 0; i <= (12 - tab); i ++) {
  171.            printf("\t");
  172.       }
  173.       printf("%d", p);
  174. }
  175.  
  176. /* the end */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement