Heap Sort Code

Heap Sort

This is a new heap sort code, you can copy it, and paste in linux, then run it.

Show code

#include <stdio.h>

/*- print function -*/
void print_array(int *pArray, int length)
{
    int i;
    for (i = 0; i < length; i++) {
        printf("%d  ", pArray[i]);
    }
    printf("\n");
}
void swap_value(int *pArray, int left, int right)
{
    int temp = pArray[left];
    pArray[left] = pArray[right];
    pArray[right] = temp;
}


void max_heap(int *pArray, int index, int length)
{
    int leftIndex = (index << 1) + 1;
    int rightIndex = (index << 1) + 2;

    /*if left inex beyond length, ignore it */
    if (leftIndex <= length-1) {
        /* check left child-node */
        if (pArray[index] < pArray[2*index+1]) {
            swap_value(pArray, index, 2*index+1);
        }
    } 
    /* only handle normal index */
    if( rightIndex <= length-1) {
        /* check right child-node */
        if (pArray[index] < pArray[2*index+2]) {
            swap_value(pArray, index, 2*index+2);
        }
    }

}

void heapify(int *pArray, int index, int length)
{
    if (length < 3) {
        /*only two elements, just return. */
        return;
    }
    if (index > length - 1) {
        return;
    }

    int i = index;
    /* recurise */
    int leftIndex = 2*i+1;
    int rightIndex = 2*i+2;
    max_heap(pArray, i, length);
    /*check sub-children match max_heap or not and adjust it. */
    heapify(pArray, leftIndex, length);
    heapify(pArray, rightIndex, length);
}

void heap_sort(int *pArray, int length)
{
    int i = length;

    while(i >= 1) {
        int j = (i/2-1);
        /*build max-top heap */
        while(j >= 0) {
            heapify(pArray, j, i);
            j--;
        }

        swap_value(pArray, 0, i-1);
        i--;
        print_array(pArray, length);
    }
}
int main(int argc, char *argv[])
{
    int aszArray[] = {60, 70, 90, 20, 80, 10};
    print_array(aszArray, 6);
    heap_sort(aszArray, 6);
    printf("-------------\n");
    print_array(aszArray, 6);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值