源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C语言实现堆排序的简单实例

  • 时间:2022-01-19 21:15 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C语言实现堆排序的简单实例
本文通过一个C语言实现堆排序的简单实例,帮助大家抛开复杂的概念,更好的理解堆排序。 实例代码如下:
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; 
}
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部