Bubble sorting in C++
Give an example of bubble sorting in C++.
1
Author: Nicolas Chabanovsky, 2010-10-20
3 answers
Judging by the implementation of the algorithm, this is not bubble_sort (not bubble), but a selection sort.
With bubbly, it would be
// Обмен СОСЕДНИХ элементов (изменив также при этом остальной код).
swap(vArray[i], vArray[i+1])
This is just a warning for those who want to stupidly copy. I have already read in other topics on sorting, where they confuse the bubble with the selection.
7
Author: Valentin, 2011-03-04 08:51:48
Bubble sorting of a vector in C++
#include <vector>
template <typename T>
inline void swap( T & arg1, T & arg2)
{
T temp = arg1;
arg1 = arg2;
arg2 = temp;
};
template <typename T>
void bubble_sort( std::vector<T> & vArray)
{
for (int i = 0; i < vArray.size(); ++i)
{
for (int j = vArray.size()-1; j > i; --j)
{
if (vArray[i] > vArray[j])
{ swap( vArray[i], vArray[j]); }
}
}
};
2
Author: Nicolas Chabanovsky, 2010-10-21 15:19:36
The generalized bubble sort looks like this:
template<typename BidirIterator, typename Compare = std::less<>>
void bubble_sort(BidirIterator first, BidirIterator last, Compare cmp = {}) {
if (first == last) return;
while (first != --last)
for (auto it = first; it != last; ++it)
if (!cmp(*it, *std::next(it)))
std::iter_swap(it, std::next(it));
}
The largest elements "pop up" at the end of the sequence, so at each iteration of the outer loop, the un-sorted part of the sequence is shortened from the end.
1
Author: Abyx, 2016-02-03 13:06:12