diff --git a/DIRECTORY.md b/DIRECTORY.md index a691a652b..0c504e8c6 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -338,7 +338,7 @@ * [Radix Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/radix_sort2.cpp) * [Random Pivot Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/random_pivot_quick_sort.cpp) * [Recursive Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/recursive_bubble_sort.cpp) - * [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort.cpp) + * [Selection Sort Iterative](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort_iterative.cpp) * [Selection Sort Recursive](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort_recursive.cpp) * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort.cpp) * [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort2.cpp) diff --git a/bit_manipulation/count_of_set_bits.cpp b/bit_manipulation/count_of_set_bits.cpp index 497346a53..f2d802061 100644 --- a/bit_manipulation/count_of_set_bits.cpp +++ b/bit_manipulation/count_of_set_bits.cpp @@ -5,7 +5,8 @@ * integer. * * @details - * We are given an integer number. We need to calculate the number of set bits in it. + * We are given an integer number. We need to calculate the number of set bits + * in it. * * A binary number consists of two digits. They are 0 & 1. Digit 1 is known as * set bit in computer terms. @@ -15,7 +16,7 @@ * @author [Prashant Thakur](https://github.com/prashant-th18) */ #include /// for assert -#include /// for IO operations +#include /// for IO operations /** * @namespace bit_manipulation * @brief Bit manipulation algorithms @@ -33,21 +34,21 @@ namespace count_of_set_bits { * @param n is the number whose set bit will be counted * @returns total number of set-bits in the binary representation of number `n` */ -std::uint64_t countSetBits(std :: int64_t n) { // int64_t is preferred over int so that - // no Overflow can be there. +std::uint64_t countSetBits( + std ::int64_t n) { // int64_t is preferred over int so that + // no Overflow can be there. - int count = 0; // "count" variable is used to count number of set-bits('1') in - // binary representation of number 'n' - while (n != 0) - { + int count = 0; // "count" variable is used to count number of set-bits('1') + // in binary representation of number 'n' + while (n != 0) { ++count; n = (n & (n - 1)); } return count; // Why this algorithm is better than the standard one? // Because this algorithm runs the same number of times as the number of - // set-bits in it. Means if my number is having "3" set bits, then this while loop - // will run only "3" times!! + // set-bits in it. Means if my number is having "3" set bits, then this + // while loop will run only "3" times!! } } // namespace count_of_set_bits } // namespace bit_manipulation diff --git a/ciphers/atbash_cipher.cpp b/ciphers/atbash_cipher.cpp index 04c330598..4f0d793f2 100644 --- a/ciphers/atbash_cipher.cpp +++ b/ciphers/atbash_cipher.cpp @@ -22,7 +22,8 @@ */ namespace ciphers { /** \namespace atbash - * \brief Functions for the [Atbash Cipher](https://en.wikipedia.org/wiki/Atbash) implementation + * \brief Functions for the [Atbash + * Cipher](https://en.wikipedia.org/wiki/Atbash) implementation */ namespace atbash { std::map atbash_cipher_map = { @@ -43,7 +44,7 @@ std::map atbash_cipher_map = { * @param text Plaintext to be encrypted * @returns encoded or decoded string */ -std::string atbash_cipher(std::string text) { +std::string atbash_cipher(const std::string& text) { std::string result; for (char letter : text) { result += atbash_cipher_map[letter]; diff --git a/data_structures/dsu_path_compression.cpp b/data_structures/dsu_path_compression.cpp index a5c0aec33..022e632a7 100644 --- a/data_structures/dsu_path_compression.cpp +++ b/data_structures/dsu_path_compression.cpp @@ -184,7 +184,7 @@ static void test1() { * @returns void */ static void test2() { - // the minimum, maximum, and size of the set + // the minimum, maximum, and size of the set uint64_t n = 10; ///< number of items dsu d(n + 1); ///< object of class disjoint sets // set 1 diff --git a/data_structures/stack_using_queue.cpp b/data_structures/stack_using_queue.cpp index 54a81a135..bd6a60e2b 100644 --- a/data_structures/stack_using_queue.cpp +++ b/data_structures/stack_using_queue.cpp @@ -3,13 +3,14 @@ * @details * Using 2 Queues inside the Stack class, we can easily implement Stack * data structure with heavy computation in push function. - * - * References used: [StudyTonight](https://www.studytonight.com/data-structures/stack-using-queue) + * + * References used: + * [StudyTonight](https://www.studytonight.com/data-structures/stack-using-queue) * @author [tushar2407](https://github.com/tushar2407) */ -#include /// for IO operations -#include /// for queue data structure -#include /// for assert +#include /// for assert +#include /// for IO operations +#include /// for queue data structure /** * @namespace data_strcutres @@ -18,66 +19,59 @@ namespace data_structures { /** * @namespace stack_using_queue - * @brief Functions for the [Stack Using Queue](https://www.studytonight.com/data-structures/stack-using-queue) implementation + * @brief Functions for the [Stack Using + * Queue](https://www.studytonight.com/data-structures/stack-using-queue) + * implementation */ namespace stack_using_queue { +/** + * @brief Stack Class implementation for basic methods of Stack Data Structure. + */ +struct Stack { + std::queue main_q; ///< stores the current state of the stack + std::queue auxiliary_q; ///< used to carry out intermediate + ///< operations to implement stack + uint32_t current_size = 0; ///< stores the current size of the stack + /** - * @brief Stack Class implementation for basic methods of Stack Data Structure. + * Returns the top most element of the stack + * @returns top element of the queue */ - struct Stack - { - std::queue main_q; ///< stores the current state of the stack - std::queue auxiliary_q; ///< used to carry out intermediate operations to implement stack - uint32_t current_size = 0; ///< stores the current size of the stack - - /** - * Returns the top most element of the stack - * @returns top element of the queue - */ - int top() - { - return main_q.front(); - } + int top() { return main_q.front(); } - /** - * @brief Inserts an element to the top of the stack. - * @param val the element that will be inserted into the stack - * @returns void - */ - void push(int val) - { - auxiliary_q.push(val); - while(!main_q.empty()) - { - auxiliary_q.push(main_q.front()); - main_q.pop(); - } - swap(main_q, auxiliary_q); - current_size++; - } - - /** - * @brief Removes the topmost element from the stack - * @returns void - */ - void pop() - { - if(main_q.empty()) { - return; - } + /** + * @brief Inserts an element to the top of the stack. + * @param val the element that will be inserted into the stack + * @returns void + */ + void push(int val) { + auxiliary_q.push(val); + while (!main_q.empty()) { + auxiliary_q.push(main_q.front()); main_q.pop(); - current_size--; } + swap(main_q, auxiliary_q); + current_size++; + } - /** - * @brief Utility function to return the current size of the stack - * @returns current size of stack - */ - int size() - { - return current_size; + /** + * @brief Removes the topmost element from the stack + * @returns void + */ + void pop() { + if (main_q.empty()) { + return; } - }; + main_q.pop(); + current_size--; + } + + /** + * @brief Utility function to return the current size of the stack + * @returns current size of stack + */ + int size() { return current_size; } +}; } // namespace stack_using_queue } // namespace data_structures @@ -85,30 +79,29 @@ namespace stack_using_queue { * @brief Self-test implementations * @returns void */ -static void test() -{ +static void test() { data_structures::stack_using_queue::Stack s; - s.push(1); /// insert an element into the stack - s.push(2); /// insert an element into the stack - s.push(3); /// insert an element into the stack - - assert(s.size()==3); /// size should be 3 - - assert(s.top()==3); /// topmost element in the stack should be 3 - - s.pop(); /// remove the topmost element from the stack - assert(s.top()==2); /// topmost element in the stack should now be 2 - - s.pop(); /// remove the topmost element from the stack - assert(s.top()==1); - - s.push(5); /// insert an element into the stack - assert(s.top()==5); /// topmost element in the stack should now be 5 - - s.pop(); /// remove the topmost element from the stack - assert(s.top()==1); /// topmost element in the stack should now be 1 - - assert(s.size()==1); /// size should be 1 + s.push(1); /// insert an element into the stack + s.push(2); /// insert an element into the stack + s.push(3); /// insert an element into the stack + + assert(s.size() == 3); /// size should be 3 + + assert(s.top() == 3); /// topmost element in the stack should be 3 + + s.pop(); /// remove the topmost element from the stack + assert(s.top() == 2); /// topmost element in the stack should now be 2 + + s.pop(); /// remove the topmost element from the stack + assert(s.top() == 1); + + s.push(5); /// insert an element into the stack + assert(s.top() == 5); /// topmost element in the stack should now be 5 + + s.pop(); /// remove the topmost element from the stack + assert(s.top() == 1); /// topmost element in the stack should now be 1 + + assert(s.size() == 1); /// size should be 1 } /** @@ -119,8 +112,7 @@ static void test() * declared above. * @returns 0 on exit */ -int main() -{ +int main() { test(); // run self-test implementations return 0; } diff --git a/math/area.cpp b/math/area.cpp index 6983cf3e4..691fe91f0 100644 --- a/math/area.cpp +++ b/math/area.cpp @@ -1,17 +1,19 @@ /** * @file - * @brief Implementations for the [area](https://en.wikipedia.org/wiki/Area) of various shapes - * @details The area of a shape is the amount of 2D space it takes up. - * All shapes have a formula to get the area of any given shape. + * @brief Implementations for the [area](https://en.wikipedia.org/wiki/Area) of + * various shapes + * @details The area of a shape is the amount of 2D space it takes up. + * All shapes have a formula to get the area of any given shape. * These implementations support multiple return types. - * + * * @author [Focusucof](https://github.com/Focusucof) */ #define _USE_MATH_DEFINES -#include /// for M_PI definition and pow() -#include /// for uint16_t datatype -#include /// for IO operations #include /// for assert +#include /// for M_PI definition and pow() +#include +#include /// for uint16_t datatype +#include /// for IO operations /** * @namespace math @@ -115,25 +117,25 @@ T cylinder_surface_area(T radius, T height) { */ static void test() { // I/O variables for testing - uint16_t int_length; // 16 bit integer length input - uint16_t int_width; // 16 bit integer width input - uint16_t int_base; // 16 bit integer base input - uint16_t int_height; // 16 bit integer height input - uint16_t int_expected; // 16 bit integer expected output - uint16_t int_area; // 16 bit integer output + uint16_t int_length = 0; // 16 bit integer length input + uint16_t int_width = 0; // 16 bit integer width input + uint16_t int_base = 0; // 16 bit integer base input + uint16_t int_height = 0; // 16 bit integer height input + uint16_t int_expected = 0; // 16 bit integer expected output + uint16_t int_area = 0; // 16 bit integer output - float float_length; // float length input - float float_expected; // float expected output - float float_area; // float output + float float_length = NAN; // float length input + float float_expected = NAN; // float expected output + float float_area = NAN; // float output - double double_length; // double length input - double double_width; // double width input - double double_radius; // double radius input - double double_height; // double height input - double double_expected; // double expected output - double double_area; // double output + double double_length = NAN; // double length input + double double_width = NAN; // double width input + double double_radius = NAN; // double radius input + double double_height = NAN; // double height input + double double_expected = NAN; // double expected output + double double_area = NAN; // double output - // 1st test + // 1st test int_length = 5; int_expected = 25; int_area = math::square_area(int_length); @@ -201,7 +203,9 @@ static void test() { // 6th test double_radius = 6; - double_expected = 113.09733552923255; // rounded down because the double datatype truncates after 14 decimal places + double_expected = + 113.09733552923255; // rounded down because the double datatype + // truncates after 14 decimal places double_area = math::circle_area(double_radius); std::cout << "AREA OF A CIRCLE" << std::endl; @@ -239,7 +243,8 @@ static void test() { // 9th test double_radius = 10.0; - double_expected = 1256.6370614359172; // rounded down because the whole value gets truncated + double_expected = 1256.6370614359172; // rounded down because the whole + // value gets truncated double_area = math::sphere_surface_area(double_radius); std::cout << "SURFACE AREA OF A SPHERE" << std::endl; diff --git a/math/integral_approximation2.cpp b/math/integral_approximation2.cpp index 706672d12..eed605e03 100644 --- a/math/integral_approximation2.cpp +++ b/math/integral_approximation2.cpp @@ -1,29 +1,34 @@ /** * @file - * @brief [Monte Carlo Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration) + * @brief [Monte Carlo + * Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration) * * @details - * In mathematics, Monte Carlo integration is a technique for numerical integration using random numbers. - * It is a particular Monte Carlo method that numerically computes a definite integral. - * While other algorithms usually evaluate the integrand at a regular grid, Monte Carlo randomly chooses points at which the integrand is evaluated. - * This method is particularly useful for higher-dimensional integrals. + * In mathematics, Monte Carlo integration is a technique for numerical + * integration using random numbers. It is a particular Monte Carlo method that + * numerically computes a definite integral. While other algorithms usually + * evaluate the integrand at a regular grid, Monte Carlo randomly chooses points + * at which the integrand is evaluated. This method is particularly useful for + * higher-dimensional integrals. * * This implementation supports arbitrary pdfs. - * These pdfs are sampled using the [Metropolis-Hastings algorithm](https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm). - * This can be swapped out by every other sampling techniques for example the inverse method. - * Metropolis-Hastings was chosen because it is the most general and can also be extended for a higher dimensional sampling space. + * These pdfs are sampled using the [Metropolis-Hastings + * algorithm](https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm). This + * can be swapped out by every other sampling techniques for example the inverse + * method. Metropolis-Hastings was chosen because it is the most general and can + * also be extended for a higher dimensional sampling space. * * @author [Domenic Zingsheim](https://github.com/DerAndereDomenic) */ -#define _USE_MATH_DEFINES /// for M_PI on windows -#include /// for math functions -#include /// for fixed size data types -#include /// for time to initialize rng -#include /// for function pointers -#include /// for std::cout -#include /// for random number generation -#include /// for std::vector +#define _USE_MATH_DEFINES /// for M_PI on windows +#include /// for math functions +#include /// for fixed size data types +#include /// for time to initialize rng +#include /// for function pointers +#include /// for std::cout +#include /// for random number generation +#include /// for std::vector /** * @namespace math @@ -32,25 +37,34 @@ namespace math { /** * @namespace monte_carlo - * @brief Functions for the [Monte Carlo Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration) implementation + * @brief Functions for the [Monte Carlo + * Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration) + * implementation */ namespace monte_carlo { -using Function = std::function; /// short-hand for std::functions used in this implementation +using Function = std::function; /// short-hand for std::functions used in this implementation /** * @brief Generate samples according to some pdf - * @details This function uses Metropolis-Hastings to generate random numbers. It generates a sequence of random numbers by using a markov chain. - * Therefore, we need to define a start_point and the number of samples we want to generate. - * Because the first samples generated by the markov chain may not be distributed according to the given pdf, one can specify how many samples + * @details This function uses Metropolis-Hastings to generate random numbers. + * It generates a sequence of random numbers by using a markov chain. Therefore, + * we need to define a start_point and the number of samples we want to + * generate. Because the first samples generated by the markov chain may not be + * distributed according to the given pdf, one can specify how many samples * should be discarded before storing samples. * @param start_point The starting point of the markov chain * @param pdf The pdf to sample * @param num_samples The number of samples to generate * @param discard How many samples should be discarded at the start - * @returns A vector of size num_samples with samples distributed according to the pdf + * @returns A vector of size num_samples with samples distributed according to + * the pdf */ -std::vector generate_samples(const double& start_point, const Function& pdf, const uint32_t& num_samples, const uint32_t& discard = 100000) { +std::vector generate_samples(const double& start_point, + const Function& pdf, + const uint32_t& num_samples, + const uint32_t& discard = 100000) { std::vector samples; samples.reserve(num_samples); @@ -61,19 +75,19 @@ std::vector generate_samples(const double& start_point, const Function& std::normal_distribution normal(0.0, 1.0); generator.seed(time(nullptr)); - for(uint32_t t = 0; t < num_samples + discard; ++t) { + for (uint32_t t = 0; t < num_samples + discard; ++t) { // Generate a new proposal according to some mutation strategy. // This is arbitrary and can be swapped. double x_dash = normal(generator) + x_t; - double acceptance_probability = std::min(pdf(x_dash)/pdf(x_t), 1.0); + double acceptance_probability = std::min(pdf(x_dash) / pdf(x_t), 1.0); double u = uniform(generator); // Accept "new state" according to the acceptance_probability - if(u <= acceptance_probability) { + if (u <= acceptance_probability) { x_t = x_dash; } - if(t >= discard) { + if (t >= discard) { samples.push_back(x_t); } } @@ -92,13 +106,17 @@ std::vector generate_samples(const double& start_point, const Function& * @param function The function to integrate * @param pdf The pdf to sample * @param num_samples The number of samples used to approximate the integral - * @returns The approximation of the integral according to 1/N \sum_{i}^N f(x_i) / p(x_i) + * @returns The approximation of the integral according to 1/N \sum_{i}^N f(x_i) + * / p(x_i) */ -double integral_monte_carlo(const double& start_point, const Function& function, const Function& pdf, const uint32_t& num_samples = 1000000) { +double integral_monte_carlo(const double& start_point, const Function& function, + const Function& pdf, + const uint32_t& num_samples = 1000000) { double integral = 0.0; - std::vector samples = generate_samples(start_point, pdf, num_samples); + std::vector samples = + generate_samples(start_point, pdf, num_samples); - for(double sample : samples) { + for (double sample : samples) { integral += function(sample) / pdf(sample); } @@ -113,8 +131,13 @@ double integral_monte_carlo(const double& start_point, const Function& function, * @returns void */ static void test() { - std::cout << "Disclaimer: Because this is a randomized algorithm," << std::endl; - std::cout << "it may happen that singular samples deviate from the true result." << std::endl << std::endl;; + std::cout << "Disclaimer: Because this is a randomized algorithm," + << std::endl; + std::cout + << "it may happen that singular samples deviate from the true result." + << std::endl + << std::endl; + ; math::monte_carlo::Function f; math::monte_carlo::Function pdf; @@ -122,60 +145,58 @@ static void test() { double lower_bound = 0, upper_bound = 0; /* \int_{-2}^{2} -x^2 + 4 dx */ - f = [&](double& x) { - return -x*x + 4.0; - }; + f = [&](double& x) { return -x * x + 4.0; }; lower_bound = -2.0; upper_bound = 2.0; pdf = [&](double& x) { - if(x >= lower_bound && x <= -1.0) { + if (x >= lower_bound && x <= -1.0) { return 0.1; } - if(x <= upper_bound && x >= 1.0) { + if (x <= upper_bound && x >= 1.0) { return 0.1; } - if(x > -1.0 && x < 1.0) { + if (x > -1.0 && x < 1.0) { return 0.4; } return 0.0; }; - integral = math::monte_carlo::integral_monte_carlo((upper_bound - lower_bound) / 2.0, f, pdf); + integral = math::monte_carlo::integral_monte_carlo( + (upper_bound - lower_bound) / 2.0, f, pdf); - std::cout << "This number should be close to 10.666666: " << integral << std::endl; + std::cout << "This number should be close to 10.666666: " << integral + << std::endl; /* \int_{0}^{1} e^x dx */ - f = [&](double& x) { - return std::exp(x); - }; + f = [&](double& x) { return std::exp(x); }; lower_bound = 0.0; upper_bound = 1.0; pdf = [&](double& x) { - if(x >= lower_bound && x <= 0.2) { + if (x >= lower_bound && x <= 0.2) { return 0.1; } - if(x > 0.2 && x <= 0.4) { + if (x > 0.2 && x <= 0.4) { return 0.4; } - if(x > 0.4 && x < upper_bound) { + if (x > 0.4 && x < upper_bound) { return 1.5; } return 0.0; }; - integral = math::monte_carlo::integral_monte_carlo((upper_bound - lower_bound) / 2.0, f, pdf); + integral = math::monte_carlo::integral_monte_carlo( + (upper_bound - lower_bound) / 2.0, f, pdf); - std::cout << "This number should be close to 1.7182818: " << integral << std::endl; + std::cout << "This number should be close to 1.7182818: " << integral + << std::endl; /* \int_{-\infty}^{\infty} sinc(x) dx, sinc(x) = sin(pi * x) / (pi * x) This is a difficult integral because of its infinite domain. Therefore, it may deviate largely from the expected result. */ - f = [&](double& x) { - return std::sin(M_PI * x) / (M_PI * x); - }; + f = [&](double& x) { return std::sin(M_PI * x) / (M_PI * x); }; pdf = [&](double& x) { return 1.0 / std::sqrt(2.0 * M_PI) * std::exp(-x * x / 2.0); @@ -183,7 +204,8 @@ static void test() { integral = math::monte_carlo::integral_monte_carlo(0.0, f, pdf, 10000000); - std::cout << "This number should be close to 1.0: " << integral << std::endl; + std::cout << "This number should be close to 1.0: " << integral + << std::endl; } /** diff --git a/range_queries/segtree.cpp b/range_queries/segtree.cpp index bc03b5428..71e6890fb 100644 --- a/range_queries/segtree.cpp +++ b/range_queries/segtree.cpp @@ -144,7 +144,7 @@ void update(std::vector *segtree, std::vector *lazy, * @returns void */ static void test() { - int64_t max = static_cast(2 * pow(2, ceil(log2(7))) - 1); + auto max = static_cast(2 * pow(2, ceil(log2(7))) - 1); assert(max == 15); std::vector arr{1, 2, 3, 4, 5, 6, 7}, lazy(max), segtree(max); @@ -172,7 +172,7 @@ int main() { uint64_t n = 0; std::cin >> n; - uint64_t max = static_cast(2 * pow(2, ceil(log2(n))) - 1); + auto max = static_cast(2 * pow(2, ceil(log2(n))) - 1); std::vector arr(n), lazy(max), segtree(max); int choice = 0; diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp deleted file mode 100644 index 3854f52e6..000000000 --- a/sorting/selection_sort.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Selection Sort - -#include -using namespace std; - -int main() { - int Array[6]; - cout << "\nEnter any 6 Numbers for Unsorted Array : "; - - // Input - for (int i = 0; i < 6; i++) { - cin >> Array[i]; - } - - // Selection Sorting - for (int i = 0; i < 6; i++) { - int min = i; - for (int j = i + 1; j < 6; j++) { - if (Array[j] < Array[min]) { - min = j; // Finding the smallest number in Array - } - } - int temp = Array[i]; - Array[i] = Array[min]; - Array[min] = temp; - } - - // Output - cout << "\nSorted Array : "; - for (int i = 0; i < 6; i++) { - cout << Array[i] << "\t"; - } -} diff --git a/sorting/selection_sort_iterative.cpp b/sorting/selection_sort_iterative.cpp new file mode 100644 index 000000000..a9adac089 --- /dev/null +++ b/sorting/selection_sort_iterative.cpp @@ -0,0 +1,126 @@ +/****************************************************************************** + * @file + * @brief Implementation of the [Selection + * sort](https://en.wikipedia.org/wiki/Selection_sort) implementation using + * swapping + * @details + * The selection sort algorithm divides the input vector into two parts: a + * sorted subvector of items which is built up from left to right at the front + * (left) of the vector, and a subvector of the remaining unsorted items that + * occupy the rest of the vector. Initially, the sorted subvector is empty, and + * the unsorted subvector is the entire input vector. The algorithm proceeds by + * finding the smallest (or largest, depending on the sorting order) element in + * the unsorted subvector, exchanging (swapping) it with the leftmost unsorted + * element (putting it in sorted order), and moving the subvector boundaries one + * element to the right. + * + * ### Implementation + * + * SelectionSort + * The algorithm divides the input vector into two parts: the subvector of items + * already sorted, which is built up from left to right. Initially, the sorted + * subvector is empty and the unsorted subvector is the entire input vector. The + * algorithm proceeds by finding the smallest element in the unsorted subvector, + * exchanging (swapping) it with the leftmost unsorted element (putting it in + * sorted order), and moving the subvector boundaries one element to the right. + * + * @author [Lajat Manekar](https://github.com/Lazeeez) + * @author Unknown author + *******************************************************************************/ +#include /// for std::is_sorted +#include /// for std::assert +#include /// for IO operations +#include /// for std::vector + +/****************************************************************************** + * @namespace sorting + * @brief Sorting algorithms + *******************************************************************************/ +namespace sorting { +/****************************************************************************** + * @brief The main function which implements Selection sort + * @param arr vector to be sorted + * @param len length of vector to be sorted + * @returns @param array resultant sorted vector + *******************************************************************************/ + +std::vector selectionSort(const std::vector &arr, + uint64_t len) { + std::vector array( + arr.begin(), + arr.end()); // declare a vector in which result will be stored + for (uint64_t it = 0; it < len; ++it) { + uint64_t min = it; // set min value + for (uint64_t it2 = it + 1; it2 < len; ++it2) { + if (array[it2] < array[min]) { // check which element is smaller + min = it2; // store index of smallest element to min + } + } + + if (min != it) { // swap if min does not match to i + uint64_t tmp = array[min]; + array[min] = array[it]; + array[it] = tmp; + } + } + + return array; // return sorted vector +} +} // namespace sorting + +/******************************************************************************* + * @brief Self-test implementations + * @returns void + *******************************************************************************/ +static void test() { + // testcase #1 + // [1, 0, 0, 1, 1, 0, 2, 1] returns [0, 0, 0, 1, 1, 1, 1, 2] + std::vector vector1 = {1, 0, 0, 1, 1, 0, 2, 1}; + uint64_t vector1size = vector1.size(); + std::cout << "1st test... "; + std::vector result_test1; + result_test1 = sorting::selectionSort(vector1, vector1size); + assert(std::is_sorted(result_test1.begin(), result_test1.end())); + std::cout << "Passed" << std::endl; + + // testcase #2 + // [19, 22, 540, 241, 156, 140, 12, 1] returns [1, 12, 19, 22, 140, 156, + // 241,540] + std::vector vector2 = {19, 22, 540, 241, 156, 140, 12, 1}; + uint64_t vector2size = vector2.size(); + std::cout << "2nd test... "; + std::vector result_test2; + result_test2 = sorting::selectionSort(vector2, vector2size); + assert(std::is_sorted(result_test2.begin(), result_test2.end())); + std::cout << "Passed" << std::endl; + + // testcase #3 + // [11, 20, 30, 41, 15, 60, 82, 15] returns [11, 15, 15, 20, 30, 41, 60, 82] + std::vector vector3 = {11, 20, 30, 41, 15, 60, 82, 15}; + uint64_t vector3size = vector3.size(); + std::cout << "3rd test... "; + std::vector result_test3; + result_test3 = sorting::selectionSort(vector3, vector3size); + assert(std::is_sorted(result_test3.begin(), result_test3.end())); + std::cout << "Passed" << std::endl; + + // testcase #4 + // [1, 9, 11, 546, 26, 65, 212, 14, -11] returns [-11, 1, 9, 11, 14, 26, 65, + // 212, 546] + std::vector vector4 = {1, 9, 11, 546, 26, 65, 212, 14}; + uint64_t vector4size = vector2.size(); + std::cout << "4th test... "; + std::vector result_test4; + result_test4 = sorting::selectionSort(vector4, vector4size); + assert(std::is_sorted(result_test4.begin(), result_test4.end())); + std::cout << "Passed" << std::endl; +} + +/******************************************************************************* + * @brief Main function + * @returns 0 on exit + *******************************************************************************/ +int main() { + test(); // run self-test implementations + return 0; +}