C++通用插入排序
C++ generic insertion sort
我创建这个是为了更好地理解排序算法和泛型函数。我已经实现了一个基本的插入排序算法,我正在尝试使它与多个数据结构(至少是列表和数组)一起工作。
由于我可以访问这样的列表:list[N]来获取值,所以我认为我需要使用迭代器。所以我正在尝试转换我的解决方案。以下是我试图修改的基本插入排序算法:
int *insertionsort(int *a)
{
for (int i = 1; i<length(a); ++i)
{
int k = a[i];
int j = i-1;
{
while (j>=0 && a[j] > k)
{
a[j+1] = a[j--];
}
a[j+1] = k;
}
return a;
}
以下是我迄今为止对通用版本的了解:
template <class T>
T insertionsort(T a)
{
for (auto i = a.begin()+1; i<a.end(); ++i)
{
auto k = i;
auto j = i-1;
while (j>=a.begin() && *j>*k)
{
(j + 1) = j--;
}
(j + 1) = k;
}
return a;
}
不幸的是,我似乎根本无法让这个通用函数正确排序。我已经看了很长一段时间了,但运气不好。想法?
发布仅供OP参考,不太可能长寿。如果你非常倾向于使用C++11,并且不喜欢打字,这可能会奏效。
template<typename Iter>
void insertion_sort(Iter first, Iter last)
{
for (Iter it = first; it != last; ++it)
std::rotate(std::upper_bound(first, it, *it), it, std::next(it));
}
所用功能的中继链接:
std::upper_bound
、std::next
和std::rotate
。享受
我认为您对去引用迭代器/指针感到困惑。这应该有效:
template <class T>
T insertionsort(T a)
{
if(a.begin() == a.end()) // return a when it's empty
return a;
for(auto i = a.begin() + 1; i < a.end(); ++i)
{
auto k = *i; // k is the value pointed by i
auto j = i - 1;
while(j >= a.begin() && *j > k)
{
*(j + 1) = *j; // writen in 2 lines for clarity
j--;
}
*(j + 1) = k;
}
return a;
}
对于更通用的解决方案,最好是传递要排序的范围,而不是要排序的东西,就像std::sort()
这样的标准算法所做的那样:
template <typename BIDIRECTIONAL_ITERATOR>
void insertionsort(BIDIRECTIONAL_ITERATOR begin , BIDIRECTIONAL_ITERATOR end) //Note that the iterators
{ //are passed by value
if( begin == end ) return; //If the range is empty, abort
for(auto i = begin + 1; i < end; ++i)
{
auto j = i - 1;
bool flag = false; //Used to abort the loop after j == begin case
while(!flag && (j != begin || (flag = j == begin)) && *j > *i)
{
*(j + 1) = *j;
j -= !flag; //If j == begin, don't decrement (Without branch)
}
*(j + 1) = *i;
}
}
函数是一个过程,不返回任何内容,对原始范围进行排序。
相关文章:
- 这是插入排序的正确实现吗?
- 使用列表 STL 递归进行插入排序
- 列表 iter 不取消引用 使用列表进行插入排序
- 如何使插入排序更快?
- 插入排序的最小交换
- 双链表C++上的插入排序
- 如何在插入排序中使用 replace() 使语句变得不必要
- C++插入排序错误功能不起作用
- 如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
- 插入排序打印错误的输出
- 从矢量末尾开始的插入排序
- 插入排序:我做错了什么?
- 插入排序的向量<unique_ptr<对时避免堆分配<>>>
- 获取有趣的输出以进行插入排序
- 插入排序算法在放入函数时的行为不同
- 插入排序的Valgrind Invalid读取尺寸8的尺寸
- 插入排序与插入/擦除?(所以我需要对一个向量进行排序,而不是手工做事,而是使用插入和擦除
- 堆排序和插入排序
- 计数Heapsort和插入排序中的复制和比较数
- 使用第二个数组C 插入排序算法