`

堆排序(c++)

阅读更多
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);
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics