1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
#include <vector>
#include <cstdlib>
template<typename Iter>
void bubble_sort(Iter start, Iter end) {
for (int i = 0; i < end - start; ++i)
for (auto it = start; it < end - 1; ++it)
if (*(it+1) < *it) {
auto tmp = std::move(*it);
*it = std::move(*(it+1));
*(it+1) = std::move(tmp);
}
}
int main() {
const int SIZE = 10;
const int SEED = 0;
std::vector<int> arr(SIZE);
std::srand(SEED);
for( size_t i = 0; i < SIZE; ++i) {
arr[i] = std::rand() % 10;
std::cout << arr[i] << (i < SIZE-1?',':' ');
}
bubble_sort(arr.begin(), arr.end());
std::cout << "\nsorted to:\n";
for( int i = 0; i < SIZE; ++i)
std::cout << arr[i] << (i < SIZE-1?',':' ');
std::cout << '\n';
int a[] {6, 2, 4, 9, 0, 7, 3, 1, 5, 8};
bubble_sort(std::begin(a), std::end(a)); // or bubble_sort(a, a + 10);
for (int n: a) std::cout << n << ' ';
std::cout << '\n';
}
| |