Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
Line 377: Line 377:


=={{header|C++}}==
=={{header|C++}}==
Uses C++11. Compile with
g++ -std=c++11 bubble.cpp
<lang cpp>#include <algorithm>
<lang cpp>#include <algorithm>
#include <iostream>
#include <iostream>
Line 384: Line 386:
template <typename RAIterator> void bubble_sort(RAIterator begin,
template <typename RAIterator> void bubble_sort(RAIterator begin,
RAIterator end) {
RAIterator end) {
bool swapped = true;
using std::swap;
while (begin != end-- && swapped) {
bool changed = true;
swapped = false;
while (begin != end-- && changed) {
changed = false;
for (auto i = begin; i != end; ++i) {
for (auto i = begin; i != end; ++i) {
if (*(i + 1) < *i) {
if (*(i + 1) < *i) {
swap(*i, *(i + 1));
std::iter_swap(i, i + 1);
changed = true;
swapped = true;
}
}
}
}