/* FUNCTION_BEG *****************************************************
函数名: TInsertSort
功能: 插入排序
算法:
实现: Snight Q:51171107
FUNCTION_END ******************************************************/
#ifndef H_INSERTSORT_H
#define H_INSERTSORT_H
/* 正序 */
template <class T>
int TInsertSortP(T* apArray, unsigned long aulSize);
/* 逆序 */
template <class T>
int TInsertSortR(T* apArray, unsigned long aulSize);
/****** Achieve ******/
template <class T>
int TInsertSortP(T* apArray, unsigned long aulSize)
{
if (NULL == apArray || aulSize <=0) return 1;
T* lpTempArray = new T[aulSize];
memset(lpTempArray, 0 , sizeof(T)*aulSize);
lpTempArray[aulSize-1] = apArray[0];
unsigned long lTempArraySize = 1;
for (unsigned long i = 1; i< aulSize; ++i)
{
for (unsigned long j = aulSize - lTempArraySize; j < aulSize; j++)
{
if (apArray[i] < lpTempArray[j])
{
memcpy(&lpTempArray[0], &lpTempArray[1], sizeof(T)* (j-1));
lpTempArray[j-1] = apArray[i];
break;
}
if(j == (aulSize - 1))
{
memcpy(&lpTempArray[0], &lpTempArray[1], sizeof(T)* (aulSize-1));
lpTempArray[j] = apArray[i];
break;
}
continue;
}
lTempArraySize++;
}
memcpy(apArray, lpTempArray, sizeof(T)*aulSize);
delete []lpTempArray;
lpTempArray = NULL;
return 1;
}
template <class T>
int TInsertSortR(T* apArray, unsigned long aulSize)
{
if (NULL == apArray || aulSize <=0) return 1;
T* lpTempArray = new T[aulSize];
memset(lpTempArray, 0 , sizeof(T)*aulSize);
lpTempArray[aulSize-1] = apArray[0];
unsigned long lTempArraySize = 1;
for (unsigned long i = 1; i< aulSize; ++i)
{
for (unsigned long j = aulSize - lTempArraySize; j < aulSize; j++)
{
if (apArray[i] > lpTempArray[j])
{
memcpy(&lpTempArray[0], &lpTempArray[1], sizeof(T)* (j-1));
lpTempArray[j-1] = apArray[i];
break;
}
if(j == (aulSize - 1))
{
memcpy(&lpTempArray[0], &lpTempArray[1], sizeof(T)* (aulSize-1));
lpTempArray[j] = apArray[i];
break;
}
continue;
}
lTempArraySize++;
}
memcpy(apArray, lpTempArray, sizeof(T)*aulSize);
delete []lpTempArray;
lpTempArray = NULL;
return 1;
}
#endif//H_INSERTSORT_H