Implementation of Heap Sort

Follow is the C++ code of heap sort:

template
void _heap_sort(T * pUnsort, size_t len) { 
    for (int i = len; i >0; --i) {
        _make_heap(pUnsort, i);
        std::swap(pUnsort[0], pUnsort[i-1]);
    }
}

template
void _make_heap(T * pUnheap, size_t len) {
    int iMax;
    int iparent = len / 2 - 1;

    // first loop
    // to detect if the right child of i is exist.
    if ((iparent >= 0) && (2*iparent + 2 < len))
        iMax = (pUnheap[2*iparent + 1] > pUnheap[2*iparent + 2]) ? (2*iparent + 1) : (2*iparent + 2);    
    // only the left child of i is exist.
    else
        iMax = 2*iparent + 1;

    // swap two elements in first loop.
    if (pUnheap[iparent] < pUnheap[iMax])
            std::swap(pUnheap[iparent], pUnheap[iMax]);  

    for (int i = --iparent; i >= 0; -- i) { 
        iMax = (pUnheap[2*i + 1] > pUnheap[2*i + 2]) ? (2*i + 1) : (2*i + 2); 
        if (pUnheap[i] < pUnheap[iMax])
            std::swap(pUnheap[i], pUnheap[iMax]);
    }
}

你可能感兴趣的:(Algorithm,C++)