java数据结构堆排序_数据结构之堆排序 - 润群的个人页面 - OSCHINA - 中文开源技术交流社区...

秉承着对知识的渴望,以及对计算机那种强烈的好奇心。。在完成MOOC大学翁凯老师的的c语言课程后,继续探索陈越姥姥的数据结构。在此,灰常感谢MOOC这个平台,让我这个高三肆业狗能够系统的学习计算机课程(sorry,有点偏题了~~~~)

上班时间有时挺忙的,但是一有时间我都会进行自身知识的补充。。。

正好过年放假了,可以把剩下的排序算法学习完~~~~想想就有点激动。。。。

这一次是对一个数组进行堆排序。。。

大体思路是循环把数组调整成最大堆,然后把第一个元素放到末尾,接着将数组长度减1,直到循环结束。

本来觉得是一个很简单的算法,结果实现起来不断的报segmentation fault(当时第一反应就是数组越界了~~)。。。。

而sbulime text下c的错误调试又不熟(printf竟然都不输出了!!!!好郁闷)

只好打开terminal进行调试。。。。

果然,就是数组越界引起的。。。

最后,记录下自己的核心代码。(嗯,以自己共勉。。)

堆排序的算法部分:

void heap_sort(int arr[], int length){

for (int i = length; i > 0; i--)

{

// build max heap....

change_array_to_max_heap(i, arr);

// put max element to tail...

int temp = arr[i-1];

arr[i-1]=arr[0];

arr[0]=temp;

}

}

建堆堆算法部分:

void change_array_to_max_heap(int array_size, int element[]){

// element[0] = 0;

// ao~~~~~~~ decreasing by step 2,for comparing the minimum heap....

for (int i = array_size; i/2>=0; i-=2)

{

int min_top_heap_index = i/2;

if (min_top_heap_index == 0 ) min_top_heap_index = 1;

// comparing the current and the sub heap...

for (int top_index = min_top_heap_index; top_index <= array_size; top_index*=2)

{

int child_left = top_index*2;

if(child_left > array_size ) break;

// if right element greater than left ....

if(child_left+1<=array_size &&

element[child_left]>element[child_left-1]){

child_left++;

}

// if parent less than child....

if(element[child_left-1] > element[top_index-1]){

// printf("child:%d,top_index:%d,child_val:%d,top_val:%d\n", child_left,top_index,element[child_left-1],element[top_index-1]);

// exchange position.....

int temp = element[child_left-1];

element[child_left-1] = element[top_index-1];

element[top_index-1] = temp;

}

}

}

}

好吧,顺便放上github的链接(哈哈,广告插入

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值