/****************************************************************************** * This program demonstrates the Insertion sort. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include #include using namespace std; vector insertion_sort(const vector list) noexcept { vector sorted_list = {}; int const LIST_SIZE = list.size(); if (LIST_SIZE > 0) { Utils::push(sorted_list, list[0]); for (int i = 1; i < LIST_SIZE; ++i) { Utils::push(sorted_list, list[i]); for (int j = i - 1; j >= 0; --j) { if (sorted_list[j] > sorted_list[j + 1]) { int const TEMP = sorted_list[j + 1]; sorted_list[j + 1] = sorted_list[j]; sorted_list[j] = TEMP; } } } } return sorted_list; } 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; list_to_sort = insertion_sort(list_to_sort); cout << "Sorted List" << endl; cout << Utils::to_string(list_to_sort) << endl; return 0; }