C language to achieve a simple example of heap sort

  • 2020-04-02 02:21:04
  • OfStack

This article through a C language to achieve a simple example of heap sort, help you to put aside the complex concept, a better understanding of heap sort.
Example code is as follows:


void FindMaxInHeap(int arr[], const int size) {   
  for (int j = size - 1; j > 0; --j) {   
    int parent = j / 2;   
    int child = j;   
    if (j < size - 1 && arr[j] < arr[j+1]) {   
      ++child;   
    }   
    if (arr[child] > arr[parent]) {   
      int tmp = arr[child];   
      arr[child] = arr[parent];   
      arr[parent] = tmp;   
    }   
  }   
}   
void HeapSort(int arr[], const int size) {   
  for (int j = size; j > 0; --j) {   
    FindMaxInHeap(arr, j);   
    int tmp = arr[0];   
    arr[0] = arr[j - 1];   
    arr[j - 1] = tmp;   
  }   
}   
 
int main() 
{ 
  int arr[] = {2, 5, 3, 12, 6, 21, 8, 1};   
  int n = sizeof(arr) / sizeof(arr[0]);   
  HeapSort(arr, n);   
  for (int j = 0; j < n; ++j) {   
    printf("%3d",arr[j]);   
  }   
  printf("n");   
return 0; 
}

Related articles: