[英]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;
}
Unfortunatley我似乎無法讓這個通用函數正確排序。 我一直在看這個,沒有運氣。 想法?
發布僅供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;
}
}
該函數是一個程序,不返回任何內容,對原始范圍進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.