diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 50199d0d4..6ba62a840 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -40,3 +40,5 @@ GuyPozner
William Boyles
+Benjamin Chislett +
\ No newline at end of file diff --git a/chapters/algorithms/bubble_sort/code/c++/bubblesort.cpp b/chapters/algorithms/bubble_sort/code/c++/bubblesort.cpp index 56df64d2e..6ba59f049 100644 --- a/chapters/algorithms/bubble_sort/code/c++/bubblesort.cpp +++ b/chapters/algorithms/bubble_sort/code/c++/bubblesort.cpp @@ -1,71 +1,39 @@ -#include -#include -#include -#include -#include +#include // rand +#include // vectors +#include // cout +#include // swap -using std::begin; -using std::end; - -template -std::vector generate_input(std::size_t size, Rng& rng) { - auto dist = std::uniform_real_distribution<>(0.0, 1.0); - - auto ret = std::vector(); - std::generate_n(std::back_inserter(ret), size, - [&rng, &dist] { return dist(rng); }); - - return ret; -} - -template -void print_range(std::ostream& os, Iter const first, Iter const last) { - os << '{'; - - if (first != last) { - os << *first; - std::for_each(first + 1, last, [&os] (double d) { os << ", " << d; }); - } - - os << "}\n"; -} - -template -void bubble_sort(Iter const first, Iter const last) { - if (first == last) { - // the empty range is vacuously sorted - return; - } - - for (;;) { +std::vector bubble_sort(std::vector unsorted_list) { + while (true) { bool is_sorted = true; - - for (auto it = first; it + 1 != last; ++it) { - // these are unsorted! gotta swap 'em - if (*(it + 1) < *it) { - using std::swap; - swap(*it, *(it + 1)); + // Sweep through the array + for (unsigned int i = 0; i < unsorted_list.size() - 1; i++) { + // If next if smaller, swap, and keep sorting + if (unsorted_list[i + 1] < unsorted_list[i]) { + std::swap(unsorted_list[i], unsorted_list[i + 1]); is_sorted = false; } } - - if (is_sorted) { - break; - } + // If we made it through without swapping anything, the list is sorted + if (is_sorted) { return unsorted_list; } } } -int main() { - std::random_device random_device; - auto rng = std::mt19937(random_device()); - - auto input = generate_input(10, rng); +int main() +{ + std::vector to_be_sorted = {}; + // Initialize and print a vector with 50 random integers of domain [0,1000] + for (int i = 0; i < 50; i++) { + int value = rand() % 1000; + std::cout << value << " "; + to_be_sorted.push_back(value); + } + std::cout << std::endl; - std::cout << "before sorting:\n"; - print_range(std::cout, begin(input), end(input)); + std::vector sorted = bubble_sort(to_be_sorted); - bubble_sort(begin(input), end(input)); + for (int i : sorted) { std::cout << i << " "; } - std::cout << "\nafter sorting:\n"; - print_range(std::cout, begin(input), end(input)); + return 0; } +