[英]Insertion sort implementation using iterators and vectors
我正在嘗試使用迭代器實現插入排序算法,但它似乎並沒有像我想象的那樣工作......你對如何實現它有任何想法嗎?
另外,我不能使用這樣的代碼: https://www.geeksforgeeks.org/insertion-sort-using-c-stl/因為我打算制作一個 animation,它會變得更加復雜。
到目前為止,這是我的源代碼:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> seq = { 5, 4, 3, 2, 1 };
std::vector<int>::iterator itj;
std::vector<int>::iterator leftmost;
// insertion sort
for (std::vector<int>::iterator iti = seq.begin() + 1; iti != seq.end(); iti = std::next(iti))
{
itj = std::prev(iti);
leftmost = iti;
while (std::distance(seq.begin(), itj) >= 0 && *itj > *leftmost)
{
std::next(itj) = itj;
itj = prev(itj);
}
std::next(itj) = leftmost;
}
// printing
for (std::vector<int>::iterator iti = seq.begin(); iti != seq.end(); iti = std::next(iti))
{
std::cout << *iti << " ";
}
}
這是一個非常優雅的插入排序實現,它使用直接從rotate上的參考頁面提升的迭代器:
// insertion sort
for (auto i = v.begin(); i != v.end(); ++i) {
std::rotate(std::upper_bound(v.begin(), i, *i), i, i+1);
}
您所要做的就是了解std::rotate
是如何工作的,這很容易理解。 (無論如何, rotate
是一個非常強大的算法,你應該感到舒服)。
這是取自 SGI STL 1的實現:
template<class Random_it, class T>
void unguarded_linear_insert(Random_it last, T val) {
auto next = last;
--next;
while (val < *next) {
*last = *next;
last = next;
--next;
}
*last = val;
}
template<class Random_it>
void linear_insert(Random_it first, Random_it last) {
auto val = *last;
if (val < *first) {
std::copy_backward(first, last, last + 1);
*first = val;
}
else
unguarded_linear_insert(last, val);
}
template<class Random_it>
void insertion_sort(Random_it first, Random_it last) {
if (first == last)
return;
for (auto i = first + 1; i != last; ++i)
linear_insert(first, i);
}
請注意如何使用val < *first
條件和std::copy_backward
來簡化unguarded_linear_insert
內的循環:在該循環中只能檢查一個條件,即val < *next
。
1在 libstdc++ 中可以找到相同的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.