/****************************************************************************** * This program demonstrates the Bubble sort. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include #include using namespace std; void bubble_sort(vector list) noexcept { for (int i = list.size() - 2; i >= 0; --i) { bool has_swap = false; for (int j = 0; j <= i; ++j) { if (list[j] > list[j + 1]) { int const TEMP = list[j + 1]; list[j + 1] = list[j]; list[j] = TEMP; has_swap = true; } } if (!has_swap) { break; } } } int main(int argc, char **argv) { if (argc != 3) { cout << "Syntax: " << argv[0] << " list_size max_int" << endl; exit(1); } int const LIST_SIZE = Utils::stoiWithDefault(string(argv[1]), 10); int const MAX_INT = Utils::stoiWithDefault(string(argv[2]), 100); vector list_to_sort = {}; srand(time(0)); cout << "Random List" << endl; for (int i = 0; i < LIST_SIZE; ++i) { Utils::push(list_to_sort, int(MAX_INT * (rand()/(RAND_MAX + 1.0)))); } cout << Utils::to_string(list_to_sort) << endl; bubble_sort(list_to_sort); cout << "Sorted List" << endl; cout << Utils::to_string(list_to_sort) << endl; return 0; }