您的位置:首页 > 编程语言 > C语言/C++

C++模板实现归并排序

2017-04-25 12:38 591 查看
归并排序的思想是将一个大的序列先进行二分法划分,直到划分到每个子序列只包含一个元素为止. 然后对序列进行依次合并,在合并的过程中实现排序.归并排序是一种典型的外部排序算法,需要额外的辅助空间来完成算法.

算法分析:

1.稳定

2.时间复杂度: O(nlog(n))

3.需要额外辅助空间来实现排序

//Mergesort
//1. Stable
//2. Time complex O(nlog(n))
//3. Need addition space's help (tempArray)
//4. In one time merge sort, when low>=high, stop
template <typename T, unsigned int size>
void Sort<T, size>::mergeSort(T* const sortArray, int low, int high)
{
if (low >= high)
{

}
else
{
int mid = (low + high) / 2;
mergeSort(sortArray, low, mid);
mergeSort(sortArray, mid + 1, high);
merge(sortArray, low, high);
}
return;
}

template <typename T, unsigned int size>
void Sort<T, size>::merge(T* const sortArray, int low, int high)
{
T* tempArray = new T[high-low+1];
int mid = (low + high) / 2;
int i = low;
int j = mid + 1;
int tempArrayIndex = 0;
while ((i <= mid) && (j <= high))
{
loopTimes++;
if (sortArray[i] <= sortArray[j])
{
tempArray[tempArrayIndex] = sortArray[i];
i++;
tempArrayIndex++;
}
else
{
tempArray[tempArrayIndex] = sortArray[j];
j++;
tempArrayIndex++;
}
}

if (i > mid)
{
while (j <= high)
{
loopTimes++;
tempArray[tempArrayIndex] = sortArray[j];
j++;
tempArrayIndex++;
}
}
else if (j > high)
{
while (i <= mid)
{
loopTimes++;
tempArray[tempArrayIndex] = sortArray[i];
i++;
tempArrayIndex++;
}
}

//tempArrayIndex = 0;
//for (int i = low; i <= high; i++)
//{
//  sortArray[i] = tempArray[tempArrayIndex];
//  tempArrayIndex++;
//}

memset(&sortArray[low], 0, sizeof(T) * (high-low+1));
memcpy(&sortArray[low], tempArray, sizeof(T) * (high-low+1));
delete[] tempArray;
tempArray = NULL;
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: