|
2 | 2 | #include <cstddef>
|
3 | 3 | #include <iostream>
|
4 | 4 | #include <iterator>
|
5 |
| -#include <random> |
6 |
| - |
7 |
| -using std::begin; |
8 |
| -using std::end; |
9 |
| - |
10 |
| -template <class Rng> |
11 |
| -std::vector<float> generate_input(std::size_t size, Rng& rng) { |
12 |
| - auto dist = std::uniform_real_distribution<>(0.0, 1.0); |
13 |
| - |
14 |
| - auto ret = std::vector<float>(); |
15 |
| - std::generate_n(std::back_inserter(ret), size, |
16 |
| - [&rng, &dist] { return dist(rng); }); |
17 |
| - |
18 |
| - return ret; |
19 |
| -} |
20 | 5 |
|
21 | 6 | template <class Iter>
|
22 |
| -void print_range(std::ostream& os, Iter const first, Iter const last) { |
23 |
| - os << '{'; |
24 |
| - |
25 |
| - if (first != last) { |
26 |
| - os << *first; |
27 |
| - std::for_each(first + 1, last, [&os] (double d) { os << ", " << d; }); |
28 |
| - } |
29 |
| - |
30 |
| - os << "}\n"; |
| 7 | +void print_range(Iter first, Iter last) { |
| 8 | + for (auto it = first; it != last; ++it) |
| 9 | + std::cout << *it << " "; |
| 10 | + std::cout << std::endl; |
31 | 11 | }
|
32 | 12 |
|
33 | 13 | template <class Iter>
|
34 |
| -void bubble_sort(Iter const first, Iter const last) { |
35 |
| - if (first == last) { |
36 |
| - // the empty range is vacuously sorted |
37 |
| - return; |
38 |
| - } |
39 |
| - |
40 |
| - for (;;) { |
41 |
| - bool is_sorted = true; |
42 |
| - |
43 |
| - for (auto it = first; it + 1 != last; ++it) { |
| 14 | +void bubble_sort(Iter first, Iter last) { |
| 15 | + for (auto it1 = first; it1 != last; ++it1) { |
| 16 | + for (auto it2 = first; it2 + 1 != last; ++it2) { |
44 | 17 | // these are unsorted! gotta swap 'em
|
45 |
| - if (*(it + 1) < *it) { |
46 |
| - using std::swap; |
47 |
| - swap(*it, *(it + 1)); |
48 |
| - is_sorted = false; |
| 18 | + if (*(it2 + 1) < *it2) { |
| 19 | + std::iter_swap(it2, it2 + 1); |
49 | 20 | }
|
50 | 21 | }
|
51 |
| - |
52 |
| - if (is_sorted) { |
53 |
| - break; |
54 |
| - } |
55 | 22 | }
|
56 | 23 | }
|
57 | 24 |
|
58 | 25 | int main() {
|
59 |
| - std::random_device random_device; |
60 |
| - auto rng = std::mt19937(random_device()); |
61 |
| - |
62 |
| - auto input = generate_input(10, rng); |
| 26 | + int input[] = {1, 45, 756, 4569, 56, 3, 8, 5, -10, -4}; |
63 | 27 |
|
64 |
| - std::cout << "before sorting:\n"; |
65 |
| - print_range(std::cout, begin(input), end(input)); |
| 28 | + std::cout << "Unsorted array:\n"; |
| 29 | + print_range(std::begin(input), std::end(input)); |
66 | 30 |
|
67 |
| - bubble_sort(begin(input), end(input)); |
| 31 | + bubble_sort(std::begin(input), std::end(input)); |
68 | 32 |
|
69 |
| - std::cout << "\nafter sorting:\n"; |
70 |
| - print_range(std::cout, begin(input), end(input)); |
| 33 | + std::cout << "\nSorted array:\n"; |
| 34 | + print_range(std::begin(input), std::end(input)); |
71 | 35 | }
|
0 commit comments