堆排序

#include <stdio.h>


void swap(int *a, int *b);
void print_arr(int *arr, int arr_len);
void heap_build(int *arr, int note, int arr_len);
void heap_sort(int *arr, int note, int arr_len);
void heap_ex(int *arr, int i, int arr_end);


int
main()
{
  int arr[] = {34, 12, 77, 85, 98, 42, 33, 18, 64, 59, 83};
  int arr_len;
  int note = 0;
  arr_len = sizeof(arr) / sizeof(arr[0]);
  print_arr(arr, arr_len);  //打印未排序前的数组
  heap_build(arr, note, arr_len - 1);
  print_arr(arr, arr_len);  //打印第一次构建大根堆后的数组
  heap_sort(arr, note, arr_len - 1);
  print_arr(arr, arr_len);  //打印排序后的数组
}


void
heap_build(int *arr, int i_note, int arr_end)
{
  //build max_heap, the note i is the heap note
  int i;
  int arr_len = arr_end + 1;
  for (i = arr_len / 2; i > 0; i-- ) {
    heap_ex(arr, i, arr_end);  //move heap_note func
  }
}


void
heap_ex(int *arr, int i, int arr_end)
{
  //the core func in this program, note_i is the key of the arr
  int note_i = i - 1;
  int child_i = 2 * note_i + 1;
  while (child_i <= arr_end) {
    if (child_i + 1 <= arr_end && arr[child_i] < arr[child_i + 1])
      child_i++;
    if (child_i <= arr_end && arr[child_i] > arr[note_i]) {
      swap(&arr[child_i], &arr[note_i]);
      note_i = child_i;
      child_i = 2 * note_i + 1;
    } else
      break;
  }
}


void
heap_sort(int *arr, int note, int arr_end)
{
  /*
  *the first value swap with the end value, 
  *than rebuild the max_heap except the end of the values which have been swaped with the first value
  */
  int i = arr_end;
  while (i >= 0) {
    swap(&arr[0], &arr[i]);
    i--;
    heap_build(arr, note, i);
  }
}




void 
swap(int *a, int *b)
{
  int tmp;
  tmp = *a;
  *a = *b;
  *b = tmp;
}


void
print_arr(int *arr, int arr_len)
{
  int i = 0;
  while (i < arr_len) {
    printf("%d ", arr[i]);
    i++;
  }
  printf("\n");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值