算法導論思考題6-2:d叉堆

C實現代碼如下:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "PrintArray.h"
#include "RANDOMIZE_IN_PLACE.h"

#define DIMENSION 5

int getParent_D(int c) {
    return (c - 1) / DIMENSION;
}
int getChildN_D(int p, int n) {
    if (n <= 0 || n > DIMENSION) {
        fprintf(stderr, "error child number %d\n", n);
    }
    return p * DIMENSION + n;
}
void swap_D(int *p1, int *p2) {
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

void max_heapify_D(int * source, int length, int loc) {
    int max = loc;
    while (loc < length) {
        for (int n = 1; n <= DIMENSION; n++) {
            if (getChildN_D(loc, n) < length && source[getChildN_D(loc, n)] > source[max]) {
                max = getChildN_D(loc, n);
            }
        }
        if (loc == max)
            return;
        swap_D(source + loc, source + max);
        loc = max;
    }
}

void build_max_heap_D(int *source, int length) {
    for (int i = getParent_D(length - 1); i >= 0; --i) {
        max_heapify_D(source, length, i);
    }
}

void heap_sort_D(int *source, int length) {
    build_max_heap_D(source, length);
    for (int i = length - 1; i > 0; i--) {
        swap_D(source, source + i);
        max_heapify_D(source, i, 0);
    }
}

int heap_maximum_D(int *source, int length) {
    build_max_heap_D(source, length);
    return source[0];
}

int heap_extract_max_D(int *source, int length) {
    int max = heap_maximum_D(source, length);
    swap_D(source, source + length - 1);
    max_heapify_D(source, length - 1, 0);
    return max;
}

void heap_increase_key_D(int *source, int length, int loc, int key) {
    if (loc >= length) {
        fprintf(stderr, "error location for change\n");
    }
    if (source[loc] > key) {
        fprintf(stderr, "new key is smaller than current key\n");
    }

    int i;
    for (i = loc; i > 0 && source[getParent_D(i)] < key; i = getParent_D(i)) {
        source[i] = source[getParent_D(i)];
    }
    source[i] = key;
}

void max_heap_insert_D(int *source, int length, int key) {
    source[length] = INT_MIN;
    heap_increase_key_D(source, length + 1, length, key);
}

int main(int argc, char const *argv[])
{
    int source[20];
    for (int i = 0; i < 20; ++i) {
        source[i] = i;
    }
    randomize_in_place(source, 20);
    printArray(source, 0, 19);
    heap_sort_D(source, 20);
    printArray(source, 0, 19);
    printf("MAX number is %d\n", heap_extract_max_D(source, 20));
    printf("MAX number is %d\n", heap_extract_max_D(source, 19));
    printf("MAX number is %d\n", heap_extract_max_D(source, 18));
    printf("MAX number is %d\n", heap_extract_max_D(source, 17));
    printf("MAX number is %d\n", heap_extract_max_D(source, 16));
    max_heap_insert_D(source, 15, 100);
    printf("MAX number is %d\n", heap_extract_max_D(source, 16));
    return 0;
}

沒有將堆放到一個結構體裏面,而是直接將一個數組抽象爲堆。各操作的複雜度可見:算法導論思考題6-2答案

發佈了71 篇原創文章 · 獲贊 32 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章