0

我有一个问题女巫堆排序。我不知道我的代码有什么问题。这个程序只改变了表格中的第二个和最后一个位置。这是我的代码(没有主要功能):

   #include<stdio.h>
#define DUZO 100000000
int heap_size;
int tab[DUZO];

void heapify(int start){
    int l, r, largest, pom;

    l = 2*start + 1;
    r = 2*start + 2;

    if((l < heap_size) && (tab[l] > tab[start]))
        largest = l;
    else
        largest = start;

    if((r <  heap_size) && (tab[r] > tab[largest]))
        largest = r;
    if(largest != start){
        pom = tab[start];
        tab[start] = tab[largest];
        tab[largest] = pom;

        heapify(largest);
    }
}

void build_max(){
    int lenght, i;
    lenght = heap_size;

    for(i = ((lenght - 1)/2); i >= 0; --i){
        heapify(i);
    }
}

void heap_sort(){
    int i;
    build_max();


    for(i = heap_size-1; i > 0; --i) {
        int tmp = tab[0];
        tab[0] = tab[i];
        tab[i] = tmp;
        --heap_size;
        heapify(0);
    }
}

感谢所有帮助。

4

1 回答 1

1
int heap_size = 6;
int tab[5];

That's calling for writing (and reading) past the end of the array, causing undefined behaviour with probably bad consequences.

It's a bad idea to have the heap size and array as a global variables, they should be arguments to the functions.

l = 2*start + 1;
r = 2*start + 2;

That's the indexing for when you have the top of the heap at index 0, but

if((l <= heap_size) && (tab[l] > tab[start]))

that check would be used if you have the top of the heap at index 1. For index 0, that should be < (also in the next check for r).

void build_max(){
    int lenght, i;
    lenght = heap_size;

    for(i = ((lenght - 1)/2); i > 0; i--){
        heapify(i);
    }
}

forgets to heapify the top, so it doesn't in general create a heap, the condition should be i >= 0.

void heap_sort(){
    int i, lenght;
    build_max();
    lenght =  heap_size;

    for(i = lenght; i > 1; i--){
        heap_size -= 1;
        heapify(i);
    }
}

doesn't swap the top of the heap in the last position, so it doesn't sort at all. The loop should look like

for(i = heap_size-1; i > 0; --i) {
    /* swap top of heap in the last position */
    int tmp = tab[0];
    tab[0] = tab[i];
    tab[i] = tmp;
    --heap_size; /* urk, but what can we do if heapify uses the global? */
    heapify(0);  /* we need to heapify from the top, since that's where the leaf landed */
}

to actually sort the array.

于 2012-10-08T17:58:04.530 回答