标签:style blog class code java color
最近一个需求里面需要实IP升序排序,用了qsort,结果是内部排序,甚至感觉排序结果不可预测性,于是自己写了一个外部排序。
需求如下:一个指针里面有N条记录,每条记录包含:IP,偏移地址,保留位,均占4个字节,且这N条记录需要按照升序排序。
算法如下:
for (int i = 1; i < m_nCount; i++ )//sort { DWORD dwPre = NULL;//pCurAddr.GetIP()+i DWORD dwNex = NULL; char cTemp[12] = {0}; char cTemp2[12] = {0}; for (int j = m_nCount - 1; j >= i; j--) { memcpy(&dwPre, pLCIndexBuf+ ((j-1)*12), 4); memcpy(&dwNex, pLCIndexBuf+(j*12), 4); if (dwNex > dwPre) { memcpy(&cTemp, pLCIndexBuf + (j*12), 12); memcpy(&cTemp2, pLCIndexBuf + ((j-1)*12), 12); memcpy(pLCIndexBuf + (j*12), cTemp2, 12); memcpy(pLCIndexBuf + ((j-1)*12), cTemp, 12); } } }
最后大家讨论,上述方法存在问题:
1.冒泡排序非最优,二分较好;
2.memcpy函数使DWORD类型IP倒序未做处理
最后还是用了qsort函数,上次使用qsort函数导致排序错误是由于下面黄色标记代码出错原因
代码如下:
qsort(&pLCIndexBuf[0], m_nCount, 12, CompareAMTIndexV6); int CompareAMTIndexV6(const void *a,const void *b) { //CAddr pCurAddr; DWORD pOne = *(DWORD*)a; DWORD pTwo = *(DWORD*)b; //first section of IP Address BYTE byTemp1 = LOBYTE(LOWORD(pOne)); BYTE byTemp2 = LOBYTE(LOWORD(pTwo)); if (byTemp1 != byTemp2) { return ((int)byTemp1 - (int)byTemp2); } //Second section of IP Address byTemp1 = HIBYTE(LOWORD(pOne)); byTemp2 = HIBYTE(LOWORD(pTwo)); if (byTemp1 != byTemp2) { return ((int)byTemp1 - (int)byTemp2); } //Third section of IP Address byTemp1 = LOBYTE(HIWORD(pOne)); byTemp2 = LOBYTE(HIWORD(pTwo)); if (byTemp1 != byTemp2) { return ((int)byTemp1 - (int)byTemp2); } //Fourth section of IP Address byTemp1 = HIBYTE(HIWORD(pOne)); byTemp2 = HIBYTE(HIWORD(pTwo)); if (byTemp1 != byTemp2) { return ((int)byTemp1 - (int)byTemp2); } return *(int*)a - *(int*)b;//升序 }
工作总结:MFC自写排序算法(升序),布布扣,bubuko.com
标签:style blog class code java color
原文地址:http://www.cnblogs.com/CocoWang/p/3708467.html