工作总结:MFC自写排序算法(升序)

时间:2024-08-01 17:03:08

最近一个需求里面需要实IP升序排序,用了qsort,结果是内部排序,甚至感觉排序结果不可预测性,于是自己写了一个外部排序。

需求如下:一个指针里面有N条记录,每条记录包含:IP,偏移地址,保留位,均占4个字节,且这N条记录需要按照升序排序。

算法如下:

for (int i = ; i < m_nCount; i++ )//sort
{
DWORD dwPre = NULL;//pCurAddr.GetIP()+i
DWORD dwNex = NULL;
char cTemp[] = {};
char cTemp2[] = {};
for (int j = m_nCount - ; j >= i; j--)
{
memcpy(&dwPre, pLCIndexBuf+ ((j-)*), );
memcpy(&dwNex, pLCIndexBuf+(j*), );
if (dwNex > dwPre)
{
memcpy(&cTemp, pLCIndexBuf + (j*), );
memcpy(&cTemp2, pLCIndexBuf + ((j-)*), );
memcpy(pLCIndexBuf + (j*), cTemp2, );
memcpy(pLCIndexBuf + ((j-)*), cTemp, );
}
}
}

最后大家讨论,上述方法存在问题:

1.冒泡排序非最优,二分较好;

2.memcpy函数使DWORD类型IP倒序未做处理

最后还是用了qsort函数,上次使用qsort函数导致排序错误是由于下面黄色标记代码出错原因

代码如下:

qsort(&pLCIndexBuf[], m_nCount, , 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;//升序
}