自己写的堆排序算法,运行出错,条件有限,望指教
时间:2011-12-14
来源:互联网
C/C++ code
代码是在http://codepad.org 测试的,但总是有错,不知道错在什么地方,望大家指教,谢谢
#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
nParent = (nChild-1)/2
因为C/C++中除法赋值给整型是直接舍弃小数部分的
3/2=1
作者: bllqbz 发布时间: 2011-12-14
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28