mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-05-16 14:14:27 +08:00
feat: Reworked/updated sorting/selection_sort.cpp. (#1613)
* Reworked selection_sort.cpp with fixes. * Added Recursive implementation for tree traversing * Fix #2 * Delete recursive_tree_traversals.cpp * Update selection_sort.cpp * Changes done in selection_sort_iterative.cpp * updating DIRECTORY.md * clang-format and clang-tidy fixes for4681e4f7* Update sorting/selection_sort_iterative.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Update sorting/selection_sort_iterative.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Update selection_sort_iterative.cpp * Update sorting/selection_sort_iterative.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Update sorting/selection_sort_iterative.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * clang-format and clang-tidy fixes forca2a7c64* Finished changes requested by ayaankhan98. * Reworked on changes. * clang-format and clang-tidy fixes forf79b79b7* Corrected errors. * Fix #2 * Fix #3 * Major Fix #3 * clang-format and clang-tidy fixes for79341db8* clang-format and clang-tidy fixes for9bdf2ce4* Update selection_sort_iterative.cpp * clang-format and clang-tidy fixes for9833d7a7* clang-format and clang-tidy fixes forb7726460Co-authored-by: David Leal <halfpacho@gmail.com> Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Abhinn Mishra <49574460+mishraabhinn@users.noreply.github.com>
This commit is contained in:
@@ -338,7 +338,7 @@
|
|||||||
* [Radix Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/radix_sort2.cpp)
|
* [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)
|
* [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)
|
* [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)
|
* [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 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)
|
* [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort2.cpp)
|
||||||
|
|||||||
@@ -5,7 +5,8 @@
|
|||||||
* integer.
|
* integer.
|
||||||
*
|
*
|
||||||
* @details
|
* @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
|
* A binary number consists of two digits. They are 0 & 1. Digit 1 is known as
|
||||||
* set bit in computer terms.
|
* set bit in computer terms.
|
||||||
@@ -15,7 +16,7 @@
|
|||||||
* @author [Prashant Thakur](https://github.com/prashant-th18)
|
* @author [Prashant Thakur](https://github.com/prashant-th18)
|
||||||
*/
|
*/
|
||||||
#include <cassert> /// for assert
|
#include <cassert> /// for assert
|
||||||
#include <iostream> /// for IO operations
|
#include <iostream> /// for IO operations
|
||||||
/**
|
/**
|
||||||
* @namespace bit_manipulation
|
* @namespace bit_manipulation
|
||||||
* @brief Bit manipulation algorithms
|
* @brief Bit manipulation algorithms
|
||||||
@@ -33,21 +34,21 @@ namespace count_of_set_bits {
|
|||||||
* @param n is the number whose set bit will be counted
|
* @param n is the number whose set bit will be counted
|
||||||
* @returns total number of set-bits in the binary representation of number `n`
|
* @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
|
std::uint64_t countSetBits(
|
||||||
// no Overflow can be there.
|
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
|
int count = 0; // "count" variable is used to count number of set-bits('1')
|
||||||
// binary representation of number 'n'
|
// in binary representation of number 'n'
|
||||||
while (n != 0)
|
while (n != 0) {
|
||||||
{
|
|
||||||
++count;
|
++count;
|
||||||
n = (n & (n - 1));
|
n = (n & (n - 1));
|
||||||
}
|
}
|
||||||
return count;
|
return count;
|
||||||
// Why this algorithm is better than the standard one?
|
// Why this algorithm is better than the standard one?
|
||||||
// Because this algorithm runs the same number of times as the number of
|
// 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
|
// set-bits in it. Means if my number is having "3" set bits, then this
|
||||||
// will run only "3" times!!
|
// while loop will run only "3" times!!
|
||||||
}
|
}
|
||||||
} // namespace count_of_set_bits
|
} // namespace count_of_set_bits
|
||||||
} // namespace bit_manipulation
|
} // namespace bit_manipulation
|
||||||
|
|||||||
@@ -22,7 +22,8 @@
|
|||||||
*/
|
*/
|
||||||
namespace ciphers {
|
namespace ciphers {
|
||||||
/** \namespace atbash
|
/** \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 {
|
namespace atbash {
|
||||||
std::map<char, char> atbash_cipher_map = {
|
std::map<char, char> atbash_cipher_map = {
|
||||||
@@ -43,7 +44,7 @@ std::map<char, char> atbash_cipher_map = {
|
|||||||
* @param text Plaintext to be encrypted
|
* @param text Plaintext to be encrypted
|
||||||
* @returns encoded or decoded string
|
* @returns encoded or decoded string
|
||||||
*/
|
*/
|
||||||
std::string atbash_cipher(std::string text) {
|
std::string atbash_cipher(const std::string& text) {
|
||||||
std::string result;
|
std::string result;
|
||||||
for (char letter : text) {
|
for (char letter : text) {
|
||||||
result += atbash_cipher_map[letter];
|
result += atbash_cipher_map[letter];
|
||||||
|
|||||||
@@ -184,7 +184,7 @@ static void test1() {
|
|||||||
* @returns void
|
* @returns void
|
||||||
*/
|
*/
|
||||||
static void test2() {
|
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
|
uint64_t n = 10; ///< number of items
|
||||||
dsu d(n + 1); ///< object of class disjoint sets
|
dsu d(n + 1); ///< object of class disjoint sets
|
||||||
// set 1
|
// set 1
|
||||||
|
|||||||
@@ -3,13 +3,14 @@
|
|||||||
* @details
|
* @details
|
||||||
* Using 2 Queues inside the Stack class, we can easily implement Stack
|
* Using 2 Queues inside the Stack class, we can easily implement Stack
|
||||||
* data structure with heavy computation in push function.
|
* 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)
|
* @author [tushar2407](https://github.com/tushar2407)
|
||||||
*/
|
*/
|
||||||
#include <iostream> /// for IO operations
|
#include <cassert> /// for assert
|
||||||
#include <queue> /// for queue data structure
|
#include <iostream> /// for IO operations
|
||||||
#include <cassert> /// for assert
|
#include <queue> /// for queue data structure
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace data_strcutres
|
* @namespace data_strcutres
|
||||||
@@ -18,66 +19,59 @@
|
|||||||
namespace data_structures {
|
namespace data_structures {
|
||||||
/**
|
/**
|
||||||
* @namespace stack_using_queue
|
* @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 {
|
namespace stack_using_queue {
|
||||||
|
/**
|
||||||
|
* @brief Stack Class implementation for basic methods of Stack Data Structure.
|
||||||
|
*/
|
||||||
|
struct Stack {
|
||||||
|
std::queue<int64_t> main_q; ///< stores the current state of the stack
|
||||||
|
std::queue<int64_t> 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
|
int top() { return main_q.front(); }
|
||||||
{
|
|
||||||
std::queue<int64_t> main_q; ///< stores the current state of the stack
|
|
||||||
std::queue<int64_t> 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();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Inserts an element to the top of the stack.
|
* @brief Inserts an element to the top of the stack.
|
||||||
* @param val the element that will be inserted into the stack
|
* @param val the element that will be inserted into the stack
|
||||||
* @returns void
|
* @returns void
|
||||||
*/
|
*/
|
||||||
void push(int val)
|
void push(int val) {
|
||||||
{
|
auxiliary_q.push(val);
|
||||||
auxiliary_q.push(val);
|
while (!main_q.empty()) {
|
||||||
while(!main_q.empty())
|
auxiliary_q.push(main_q.front());
|
||||||
{
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
main_q.pop();
|
main_q.pop();
|
||||||
current_size--;
|
|
||||||
}
|
}
|
||||||
|
swap(main_q, auxiliary_q);
|
||||||
|
current_size++;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Utility function to return the current size of the stack
|
* @brief Removes the topmost element from the stack
|
||||||
* @returns current size of stack
|
* @returns void
|
||||||
*/
|
*/
|
||||||
int size()
|
void pop() {
|
||||||
{
|
if (main_q.empty()) {
|
||||||
return current_size;
|
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 stack_using_queue
|
||||||
} // namespace data_structures
|
} // namespace data_structures
|
||||||
|
|
||||||
@@ -85,30 +79,29 @@ namespace stack_using_queue {
|
|||||||
* @brief Self-test implementations
|
* @brief Self-test implementations
|
||||||
* @returns void
|
* @returns void
|
||||||
*/
|
*/
|
||||||
static void test()
|
static void test() {
|
||||||
{
|
|
||||||
data_structures::stack_using_queue::Stack s;
|
data_structures::stack_using_queue::Stack s;
|
||||||
s.push(1); /// insert an element into the stack
|
s.push(1); /// insert an element into the stack
|
||||||
s.push(2); /// insert an element into the stack
|
s.push(2); /// insert an element into the stack
|
||||||
s.push(3); /// 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.size() == 3); /// size should be 3
|
||||||
|
|
||||||
assert(s.top()==3); /// topmost element in the stack should be 3
|
assert(s.top() == 3); /// topmost element in the stack should be 3
|
||||||
|
|
||||||
s.pop(); /// remove the topmost element from the stack
|
s.pop(); /// remove the topmost element from the stack
|
||||||
assert(s.top()==2); /// topmost element in the stack should now be 2
|
assert(s.top() == 2); /// topmost element in the stack should now be 2
|
||||||
|
|
||||||
s.pop(); /// remove the topmost element from the stack
|
s.pop(); /// remove the topmost element from the stack
|
||||||
assert(s.top()==1);
|
assert(s.top() == 1);
|
||||||
|
|
||||||
s.push(5); /// insert an element into the stack
|
s.push(5); /// insert an element into the stack
|
||||||
assert(s.top()==5); /// topmost element in the stack should now be 5
|
assert(s.top() == 5); /// topmost element in the stack should now be 5
|
||||||
|
|
||||||
s.pop(); /// remove the topmost element from the stack
|
s.pop(); /// remove the topmost element from the stack
|
||||||
assert(s.top()==1); /// topmost element in the stack should now be 1
|
assert(s.top() == 1); /// topmost element in the stack should now be 1
|
||||||
|
|
||||||
assert(s.size()==1); /// size should be 1
|
assert(s.size() == 1); /// size should be 1
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -119,8 +112,7 @@ static void test()
|
|||||||
* declared above.
|
* declared above.
|
||||||
* @returns 0 on exit
|
* @returns 0 on exit
|
||||||
*/
|
*/
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
test(); // run self-test implementations
|
test(); // run self-test implementations
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* @file
|
* @file
|
||||||
* @brief Implementations for the [area](https://en.wikipedia.org/wiki/Area) of various shapes
|
* @brief Implementations for the [area](https://en.wikipedia.org/wiki/Area) of
|
||||||
* @details The area of a shape is the amount of 2D space it takes up.
|
* various shapes
|
||||||
* All shapes have a formula to get the area of any given shape.
|
* @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.
|
* These implementations support multiple return types.
|
||||||
*
|
*
|
||||||
* @author [Focusucof](https://github.com/Focusucof)
|
* @author [Focusucof](https://github.com/Focusucof)
|
||||||
*/
|
*/
|
||||||
#define _USE_MATH_DEFINES
|
#define _USE_MATH_DEFINES
|
||||||
#include <cmath> /// for M_PI definition and pow()
|
|
||||||
#include <cstdint> /// for uint16_t datatype
|
|
||||||
#include <iostream> /// for IO operations
|
|
||||||
#include <cassert> /// for assert
|
#include <cassert> /// for assert
|
||||||
|
#include <cmath> /// for M_PI definition and pow()
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdint> /// for uint16_t datatype
|
||||||
|
#include <iostream> /// for IO operations
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace math
|
* @namespace math
|
||||||
@@ -115,25 +117,25 @@ T cylinder_surface_area(T radius, T height) {
|
|||||||
*/
|
*/
|
||||||
static void test() {
|
static void test() {
|
||||||
// I/O variables for testing
|
// I/O variables for testing
|
||||||
uint16_t int_length; // 16 bit integer length input
|
uint16_t int_length = 0; // 16 bit integer length input
|
||||||
uint16_t int_width; // 16 bit integer width input
|
uint16_t int_width = 0; // 16 bit integer width input
|
||||||
uint16_t int_base; // 16 bit integer base input
|
uint16_t int_base = 0; // 16 bit integer base input
|
||||||
uint16_t int_height; // 16 bit integer height input
|
uint16_t int_height = 0; // 16 bit integer height input
|
||||||
uint16_t int_expected; // 16 bit integer expected output
|
uint16_t int_expected = 0; // 16 bit integer expected output
|
||||||
uint16_t int_area; // 16 bit integer output
|
uint16_t int_area = 0; // 16 bit integer output
|
||||||
|
|
||||||
float float_length; // float length input
|
float float_length = NAN; // float length input
|
||||||
float float_expected; // float expected output
|
float float_expected = NAN; // float expected output
|
||||||
float float_area; // float output
|
float float_area = NAN; // float output
|
||||||
|
|
||||||
double double_length; // double length input
|
double double_length = NAN; // double length input
|
||||||
double double_width; // double width input
|
double double_width = NAN; // double width input
|
||||||
double double_radius; // double radius input
|
double double_radius = NAN; // double radius input
|
||||||
double double_height; // double height input
|
double double_height = NAN; // double height input
|
||||||
double double_expected; // double expected output
|
double double_expected = NAN; // double expected output
|
||||||
double double_area; // double output
|
double double_area = NAN; // double output
|
||||||
|
|
||||||
// 1st test
|
// 1st test
|
||||||
int_length = 5;
|
int_length = 5;
|
||||||
int_expected = 25;
|
int_expected = 25;
|
||||||
int_area = math::square_area(int_length);
|
int_area = math::square_area(int_length);
|
||||||
@@ -201,7 +203,9 @@ static void test() {
|
|||||||
|
|
||||||
// 6th test
|
// 6th test
|
||||||
double_radius = 6;
|
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);
|
double_area = math::circle_area(double_radius);
|
||||||
|
|
||||||
std::cout << "AREA OF A CIRCLE" << std::endl;
|
std::cout << "AREA OF A CIRCLE" << std::endl;
|
||||||
@@ -239,7 +243,8 @@ static void test() {
|
|||||||
|
|
||||||
// 9th test
|
// 9th test
|
||||||
double_radius = 10.0;
|
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);
|
double_area = math::sphere_surface_area(double_radius);
|
||||||
|
|
||||||
std::cout << "SURFACE AREA OF A SPHERE" << std::endl;
|
std::cout << "SURFACE AREA OF A SPHERE" << std::endl;
|
||||||
|
|||||||
@@ -1,29 +1,34 @@
|
|||||||
/**
|
/**
|
||||||
* @file
|
* @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
|
* @details
|
||||||
* In mathematics, Monte Carlo integration is a technique for numerical integration using random numbers.
|
* In mathematics, Monte Carlo integration is a technique for numerical
|
||||||
* It is a particular Monte Carlo method that numerically computes a definite integral.
|
* integration using random numbers. It is a particular Monte Carlo method that
|
||||||
* While other algorithms usually evaluate the integrand at a regular grid, Monte Carlo randomly chooses points at which the integrand is evaluated.
|
* numerically computes a definite integral. While other algorithms usually
|
||||||
* This method is particularly useful for higher-dimensional integrals.
|
* 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.
|
* This implementation supports arbitrary pdfs.
|
||||||
* These pdfs are sampled using the [Metropolis-Hastings algorithm](https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm).
|
* These pdfs are sampled using the [Metropolis-Hastings
|
||||||
* This can be swapped out by every other sampling techniques for example the inverse method.
|
* algorithm](https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm). This
|
||||||
* Metropolis-Hastings was chosen because it is the most general and can also be extended for a higher dimensional sampling space.
|
* 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)
|
* @author [Domenic Zingsheim](https://github.com/DerAndereDomenic)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#define _USE_MATH_DEFINES /// for M_PI on windows
|
#define _USE_MATH_DEFINES /// for M_PI on windows
|
||||||
#include <cmath> /// for math functions
|
#include <cmath> /// for math functions
|
||||||
#include <cstdint> /// for fixed size data types
|
#include <cstdint> /// for fixed size data types
|
||||||
#include <ctime> /// for time to initialize rng
|
#include <ctime> /// for time to initialize rng
|
||||||
#include <functional> /// for function pointers
|
#include <functional> /// for function pointers
|
||||||
#include <iostream> /// for std::cout
|
#include <iostream> /// for std::cout
|
||||||
#include <random> /// for random number generation
|
#include <random> /// for random number generation
|
||||||
#include <vector> /// for std::vector
|
#include <vector> /// for std::vector
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace math
|
* @namespace math
|
||||||
@@ -32,25 +37,34 @@
|
|||||||
namespace math {
|
namespace math {
|
||||||
/**
|
/**
|
||||||
* @namespace monte_carlo
|
* @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 {
|
namespace monte_carlo {
|
||||||
|
|
||||||
using Function = std::function<double(double&)>; /// short-hand for std::functions used in this implementation
|
using Function = std::function<double(
|
||||||
|
double&)>; /// short-hand for std::functions used in this implementation
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Generate samples according to some pdf
|
* @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.
|
* @details This function uses Metropolis-Hastings to generate random numbers.
|
||||||
* Therefore, we need to define a start_point and the number of samples we want to generate.
|
* It generates a sequence of random numbers by using a markov chain. Therefore,
|
||||||
* Because the first samples generated by the markov chain may not be distributed according to the given pdf, one can specify how many samples
|
* 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.
|
* should be discarded before storing samples.
|
||||||
* @param start_point The starting point of the markov chain
|
* @param start_point The starting point of the markov chain
|
||||||
* @param pdf The pdf to sample
|
* @param pdf The pdf to sample
|
||||||
* @param num_samples The number of samples to generate
|
* @param num_samples The number of samples to generate
|
||||||
* @param discard How many samples should be discarded at the start
|
* @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<double> generate_samples(const double& start_point, const Function& pdf, const uint32_t& num_samples, const uint32_t& discard = 100000) {
|
std::vector<double> generate_samples(const double& start_point,
|
||||||
|
const Function& pdf,
|
||||||
|
const uint32_t& num_samples,
|
||||||
|
const uint32_t& discard = 100000) {
|
||||||
std::vector<double> samples;
|
std::vector<double> samples;
|
||||||
samples.reserve(num_samples);
|
samples.reserve(num_samples);
|
||||||
|
|
||||||
@@ -61,19 +75,19 @@ std::vector<double> generate_samples(const double& start_point, const Function&
|
|||||||
std::normal_distribution<double> normal(0.0, 1.0);
|
std::normal_distribution<double> normal(0.0, 1.0);
|
||||||
generator.seed(time(nullptr));
|
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.
|
// Generate a new proposal according to some mutation strategy.
|
||||||
// This is arbitrary and can be swapped.
|
// This is arbitrary and can be swapped.
|
||||||
double x_dash = normal(generator) + x_t;
|
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);
|
double u = uniform(generator);
|
||||||
|
|
||||||
// Accept "new state" according to the acceptance_probability
|
// Accept "new state" according to the acceptance_probability
|
||||||
if(u <= acceptance_probability) {
|
if (u <= acceptance_probability) {
|
||||||
x_t = x_dash;
|
x_t = x_dash;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(t >= discard) {
|
if (t >= discard) {
|
||||||
samples.push_back(x_t);
|
samples.push_back(x_t);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -92,13 +106,17 @@ std::vector<double> generate_samples(const double& start_point, const Function&
|
|||||||
* @param function The function to integrate
|
* @param function The function to integrate
|
||||||
* @param pdf The pdf to sample
|
* @param pdf The pdf to sample
|
||||||
* @param num_samples The number of samples used to approximate the integral
|
* @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;
|
double integral = 0.0;
|
||||||
std::vector<double> samples = generate_samples(start_point, pdf, num_samples);
|
std::vector<double> samples =
|
||||||
|
generate_samples(start_point, pdf, num_samples);
|
||||||
|
|
||||||
for(double sample : samples) {
|
for (double sample : samples) {
|
||||||
integral += function(sample) / pdf(sample);
|
integral += function(sample) / pdf(sample);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,8 +131,13 @@ double integral_monte_carlo(const double& start_point, const Function& function,
|
|||||||
* @returns void
|
* @returns void
|
||||||
*/
|
*/
|
||||||
static void test() {
|
static void test() {
|
||||||
std::cout << "Disclaimer: Because this is a randomized algorithm," << std::endl;
|
std::cout << "Disclaimer: Because this is a randomized algorithm,"
|
||||||
std::cout << "it may happen that singular samples deviate from the true result." << std::endl << std::endl;;
|
<< 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 f;
|
||||||
math::monte_carlo::Function pdf;
|
math::monte_carlo::Function pdf;
|
||||||
@@ -122,60 +145,58 @@ static void test() {
|
|||||||
double lower_bound = 0, upper_bound = 0;
|
double lower_bound = 0, upper_bound = 0;
|
||||||
|
|
||||||
/* \int_{-2}^{2} -x^2 + 4 dx */
|
/* \int_{-2}^{2} -x^2 + 4 dx */
|
||||||
f = [&](double& x) {
|
f = [&](double& x) { return -x * x + 4.0; };
|
||||||
return -x*x + 4.0;
|
|
||||||
};
|
|
||||||
|
|
||||||
lower_bound = -2.0;
|
lower_bound = -2.0;
|
||||||
upper_bound = 2.0;
|
upper_bound = 2.0;
|
||||||
pdf = [&](double& x) {
|
pdf = [&](double& x) {
|
||||||
if(x >= lower_bound && x <= -1.0) {
|
if (x >= lower_bound && x <= -1.0) {
|
||||||
return 0.1;
|
return 0.1;
|
||||||
}
|
}
|
||||||
if(x <= upper_bound && x >= 1.0) {
|
if (x <= upper_bound && x >= 1.0) {
|
||||||
return 0.1;
|
return 0.1;
|
||||||
}
|
}
|
||||||
if(x > -1.0 && x < 1.0) {
|
if (x > -1.0 && x < 1.0) {
|
||||||
return 0.4;
|
return 0.4;
|
||||||
}
|
}
|
||||||
return 0.0;
|
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 */
|
/* \int_{0}^{1} e^x dx */
|
||||||
f = [&](double& x) {
|
f = [&](double& x) { return std::exp(x); };
|
||||||
return std::exp(x);
|
|
||||||
};
|
|
||||||
|
|
||||||
lower_bound = 0.0;
|
lower_bound = 0.0;
|
||||||
upper_bound = 1.0;
|
upper_bound = 1.0;
|
||||||
pdf = [&](double& x) {
|
pdf = [&](double& x) {
|
||||||
if(x >= lower_bound && x <= 0.2) {
|
if (x >= lower_bound && x <= 0.2) {
|
||||||
return 0.1;
|
return 0.1;
|
||||||
}
|
}
|
||||||
if(x > 0.2 && x <= 0.4) {
|
if (x > 0.2 && x <= 0.4) {
|
||||||
return 0.4;
|
return 0.4;
|
||||||
}
|
}
|
||||||
if(x > 0.4 && x < upper_bound) {
|
if (x > 0.4 && x < upper_bound) {
|
||||||
return 1.5;
|
return 1.5;
|
||||||
}
|
}
|
||||||
return 0.0;
|
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)
|
/* \int_{-\infty}^{\infty} sinc(x) dx, sinc(x) = sin(pi * x) / (pi * x)
|
||||||
This is a difficult integral because of its infinite domain.
|
This is a difficult integral because of its infinite domain.
|
||||||
Therefore, it may deviate largely from the expected result.
|
Therefore, it may deviate largely from the expected result.
|
||||||
*/
|
*/
|
||||||
f = [&](double& x) {
|
f = [&](double& x) { return std::sin(M_PI * x) / (M_PI * x); };
|
||||||
return std::sin(M_PI * x) / (M_PI * x);
|
|
||||||
};
|
|
||||||
|
|
||||||
pdf = [&](double& x) {
|
pdf = [&](double& x) {
|
||||||
return 1.0 / std::sqrt(2.0 * M_PI) * std::exp(-x * x / 2.0);
|
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);
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ void update(std::vector<int64_t> *segtree, std::vector<int64_t> *lazy,
|
|||||||
* @returns void
|
* @returns void
|
||||||
*/
|
*/
|
||||||
static void test() {
|
static void test() {
|
||||||
int64_t max = static_cast<int64_t>(2 * pow(2, ceil(log2(7))) - 1);
|
auto max = static_cast<int64_t>(2 * pow(2, ceil(log2(7))) - 1);
|
||||||
assert(max == 15);
|
assert(max == 15);
|
||||||
|
|
||||||
std::vector<int64_t> arr{1, 2, 3, 4, 5, 6, 7}, lazy(max), segtree(max);
|
std::vector<int64_t> arr{1, 2, 3, 4, 5, 6, 7}, lazy(max), segtree(max);
|
||||||
@@ -172,7 +172,7 @@ int main() {
|
|||||||
uint64_t n = 0;
|
uint64_t n = 0;
|
||||||
std::cin >> n;
|
std::cin >> n;
|
||||||
|
|
||||||
uint64_t max = static_cast<uint64_t>(2 * pow(2, ceil(log2(n))) - 1);
|
auto max = static_cast<uint64_t>(2 * pow(2, ceil(log2(n))) - 1);
|
||||||
std::vector<int64_t> arr(n), lazy(max), segtree(max);
|
std::vector<int64_t> arr(n), lazy(max), segtree(max);
|
||||||
|
|
||||||
int choice = 0;
|
int choice = 0;
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
// Selection Sort
|
|
||||||
|
|
||||||
#include <iostream>
|
|
||||||
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";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
126
sorting/selection_sort_iterative.cpp
Normal file
126
sorting/selection_sort_iterative.cpp
Normal file
@@ -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 <algorithm> /// for std::is_sorted
|
||||||
|
#include <cassert> /// for std::assert
|
||||||
|
#include <iostream> /// for IO operations
|
||||||
|
#include <vector> /// 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<uint64_t> selectionSort(const std::vector<uint64_t> &arr,
|
||||||
|
uint64_t len) {
|
||||||
|
std::vector<uint64_t> 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<uint64_t> vector1 = {1, 0, 0, 1, 1, 0, 2, 1};
|
||||||
|
uint64_t vector1size = vector1.size();
|
||||||
|
std::cout << "1st test... ";
|
||||||
|
std::vector<uint64_t> 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<uint64_t> vector2 = {19, 22, 540, 241, 156, 140, 12, 1};
|
||||||
|
uint64_t vector2size = vector2.size();
|
||||||
|
std::cout << "2nd test... ";
|
||||||
|
std::vector<uint64_t> 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<uint64_t> vector3 = {11, 20, 30, 41, 15, 60, 82, 15};
|
||||||
|
uint64_t vector3size = vector3.size();
|
||||||
|
std::cout << "3rd test... ";
|
||||||
|
std::vector<uint64_t> 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<uint64_t> vector4 = {1, 9, 11, 546, 26, 65, 212, 14};
|
||||||
|
uint64_t vector4size = vector2.size();
|
||||||
|
std::cout << "4th test... ";
|
||||||
|
std::vector<uint64_t> 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;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user