Guest User

Untitled

a guest
May 17th, 2016
803
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. void heapSort(int *A, int n)       // 힙 정렬에 필요한 함수 호출
  2. {
  3.  int i, tmp;
  4.  int static r = 0;
  5.  buildHeap(A, n);
  6.  for (i = n; i > 0; i--)          // 과정2-1) 정렬 시키기
  7.  {
  8.   tmp = A[i];
  9.   A[i] = A[0];
  10.   A[0] = tmp;
  11.   printf("Make Sort[%d] : ", ++r);  
  12.   see(A, n);
  13.   heapify(A, 0, i - 1);    // 과정2-2) 정렬 후 힙을 유지시키기
  14.  }
  15. }
  16.  
  17. void buildHeap(int *A, int n)       // 과정1-1) 힙이 되도록 알맞게 호출
  18. {
  19.  int i;
  20.  int static k = 0;
  21.  for (i = n / 2; i >= 0; i--){
  22.   heapify(A, i,n);
  23.   printf("Make Heap[%d] : ", ++k);
  24.   see(A, n);
  25.  }
  26. }
  27.  
  28. void heapify(int *A, int k, int n)   // 과정1-2) 힙 만들기
  29. {
  30.  int tmp;
  31.  int smaller;
  32.  int Left = k * 2 + 1;
  33.  int Right = k * 2 + 2;
  34.  if (Right <= n)
  35.  {
  36.   if (A[Right] < A[Left])
  37.    smaller = Right;
  38.   else
  39.    smaller = Left;
  40.  }
  41.  else if (Left <= n)
  42.   smaller = Left;
  43.  else
  44.   return;
  45.  if (A[k] > A[smaller])
  46.  {
  47.   tmp = A[k];
  48.   A[k] = A[smaller];
  49.   A[smaller] = tmp;
  50.   heapify(A, smaller, n);
  51.  }
  52. }
  53.  
  54. void see(int *A, int n)            // 결과 호출
  55. {
  56.  int i;
  57.  for (i = 0; i <= n; i++)
  58.   printf("%d ", A[i]);
  59.  printf("\n");
  60. }
Advertisement
Add Comment
Please, Sign In to add comment