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

C++模板实现直接插入排序

2017-04-18 21:58 495 查看
排序是数据结构中的重要章节.涉及到多种排序算法.本小节讲述直接插入排序的算法及实现.

直接插入排序的思想是,插入的元素插入到一个已经排列有序的数组中,从数组末尾开始进行比较,如果发现插入的数小于被比较的数,则两数交换位置,直到没有发生交换,算法终止.

算法是稳定的,时间复杂度为O(n2),空间复杂度为O(n2),内部排序,不需要额外空间.

//Dierect Insert Sort
//1. Stable
//2. Compare times will different as original sequence different, O(n2)
//3. Move times will different as original sequence different, O(n2)
//4. Terminate condition: inner loop, new value not small than compared value
template<typename T>
void Sort<T>::directInsertSort(T* const sortArray, const unsigned int size)
{
for (unsigned int i = 0; i < size; i++)
{
T flag = sortArray[i];
for (unsigned int j = i - 1; j >= 0; j--)
{
loopTimes++;
if (flag < sortArray[j])
{
sortArray[j + 1] = sortArray[j];
sortArray[j] = flag;
moveTimes++;
}
else
{
break;
}
}
}
}


程序运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: