/****************************************************************************** * This program demonstrates the Insertion sort. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #include "Utils.hpp" #include #include #include #include #include using namespace std; vector insertionSort(const vector &list) noexcept { vector sortedList = {}; int const listSize = list.size(); if (listSize > 0) { Utils::push(sortedList, list[0]); for (int i = 1; i < listSize; ++i) { Utils::push(sortedList, list[i]); for (int j = i - 1; j >= 0; --j) { if (sortedList[j] > sortedList[j + 1]) { int const temp = sortedList[j + 1]; sortedList[j + 1] = sortedList[j]; sortedList[j] = temp; } } } } return sortedList; } int main(int argc, char **argv) { if (argc != 3) { cout << "Syntax: " << argv[0] << " list_size max_int" << endl; exit(1); } int const listSize = Utils::stoiWithDefault(string(argv[1]), 10); int const maxInt = Utils::stoiWithDefault(string(argv[2]), 100); vector listToSort = {}; srand(time(0)); cout << "Random List" << endl; for (int i = 0; i < listSize; ++i) { Utils::push(listToSort, int(maxInt * (rand()/(RAND_MAX + 1.0)))); } cout << Utils::to_string(listToSort) << endl; listToSort = insertionSort(listToSort); cout << "Sorted List" << endl; cout << Utils::to_string(listToSort) << endl; return 0; }