ITeye博客

堆排序(c++)

wanran · 2011-05-22 16:13 · Algorithm · 编程语言 · Markdown


void heapify(int list[], int low, int high) {
    int largeIndex;
    int temp = list[low];
    largeIndex = 2*low + 1;
    while(largeIndex<=high) {
        if(largeIndex<high)
            if(list[largeindex]<list[largeindex+1])
                largeIndex = largeIndex + 1;

        if(temp > list[largeindex])
            break;
        else {
            list[low] = list[largeindex];
            low = largeIndex;
            largeIndex = 2*low + 1;
        }
    }
    list[low] = temp;
}

void buildHeap(int list[], int length) {
    int index;
    for(index = length/2-1; index>=0; index--) {
        heapify(list, index, length-1);
    }
}

void heapSort(int list[], int length) {
    int lastOutOfOrder;
    int temp;
    buildHeap(list, length);

    for(lastOutOfOrder=length-1; lastOutOfOrder>=0; lastOutOfOrder--) {
        temp = list[lastoutoforder];
        list[lastoutoforder] = list[0];
        list[0] = temp;
        heapify(list, 0, lastOutOfOrder-1);
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。