数据结构之堆排序
為什么80%的碼農都做不了架構師?>>> ??
秉承著對知識的渴望,以及對計算機那種強烈的好奇心。。在完成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的鏈接(哈哈,廣告插入
heap struct
?
轉載于:https://my.oschina.net/runqun/blog/612768
總結
- 上一篇: Matlab与神经网络入门
- 下一篇: MySQL 性能 细节 考量 (更新中