A Za, A Za, Fighting...

坚信:勤能补拙

2011排序-堆排序

堆排序: 时间复杂度 O(nlogn),非稳定排序

比如:3 27 36 27
如果堆顶3先输出,则,第三层的27(最后一个27)跑到堆顶,然后堆稳定,继续输出堆顶,是刚才那个27,这样说明后面的27先于第二个位置的27输出,不稳定。

#define LEFT(i) (((i)<<1)+1)
#define RIGHT(i) (((i)+1)<<1)
#define PARENT(i) (((i)-1)>>1)

void
min_heapify(
int index, int *heap, int heap_size) //precondition: LEFT(index) and RIGHT(index) are both already min-heap
{
    
int min = index;
    
if(LEFT(index)<heap_size && heap[LEFT(index)]<heap[min])
        min 
= LEFT(index);
    
if(RIGHT(index)<heap_size && heap[RIGHT(index)]<heap[min])
        min 
= RIGHT(index);

    
if(min != index) {
        swap(heap
+min, heap+index);
        min_heapify(min, heap, heap_size);
    }
}

void
build_heap(
int *heap, int heap_size)
{
    
int i = (heap_size>>1);
    
for( ; i>=0--i)
        min_heapify(i, heap, heap_size);
}

void
heap_sort(
int *heap, int heap_size)
{
    build_heap(heap, heap_size);

    
while(heap_size > 1) {
        swap(heap, heap
+heap_size-1);
        
--heap_size;
        min_heapify(
0, heap, heap_size);
    }
}

posted on 2011-07-29 20:25 simplyzhao 阅读(88) 评论(0)  编辑 收藏 引用 所属分类: R_找工复习2011


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2011年7月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜