+ -
当前位置:首页 → 问答吧 → 自己写的堆排序算法,运行出错,条件有限,望指教

自己写的堆排序算法,运行出错,条件有限,望指教

时间:2011-12-14

来源:互联网

C/C++ code
#include <iostream>

using namespace std;

void Output(int array[], int nLength) {
    for(int i = 0; i<nLength;i++)
        cout<<array[i]<<" ";
    cout<<endl;
}

class CSorter
{
private:
    inline void HeapAdjust(int array[], int nLength) {
        int j = nLength - 1;
        int *pChild = &array[j];
        int *pParent = &array[j/2-1];
        for(; nLength > 1; nLength--) {
            if(*pChild > *pParent)
                Swap(pChild, pParent);
            pChild--;
            if(j%2 == 1)
                pParent--;
        }
    }

    inline void Swap(int *p1, int *p2) {
        int nTemp = *p1;
        *p1 = *p2;
        *p2 = nTemp;
    }

public:
    void HeapSort(int array[], int nLength) {
        for(; nLength > 1; nLength--) {
            cout<<nLength<<endl;
            HeapAdjust(array, nLength);
            Swap(array, &array[nLength - 1]);
        }
    }
};

int main() {
    CSorter sSorter;
    int array[] = {19,95,10,27,26,9,5};
    cout<<array<<endl;
    sSorter.HeapSort(array, sizeof(array)/sizeof(int));
    cout<<array<<endl;
    return 0;
}


代码是在http://codepad.org 测试的,但总是有错,不知道错在什么地方,望大家指教,谢谢

作者: bllqbz   发布时间: 2011-12-14

发现错在哪里了,
nParent = (nChild-1)/2

因为C/C++中除法赋值给整型是直接舍弃小数部分的
3/2=1

作者: bllqbz   发布时间: 2011-12-14