From c6a8a6841c7049bd6f26fd0412f9a06360df0cbf Mon Sep 17 00:00:00 2001 From: Swastika Gupta <64654203+Swastyy@users.noreply.github.com> Date: Sun, 4 Jul 2021 17:18:47 +0530 Subject: [PATCH] Create wave_sort.cpp --- sorting/wave_sort.cpp | 92 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 sorting/wave_sort.cpp diff --git a/sorting/wave_sort.cpp b/sorting/wave_sort.cpp new file mode 100644 index 000000000..e9f54a929 --- /dev/null +++ b/sorting/wave_sort.cpp @@ -0,0 +1,92 @@ +/** + * @file + * @brief Implementation of [Wave sort] algorithm + * @details + * Wave Sort is a sorting algorithm that works in \f$O(nlogn)\f$ time assuming the sort function used works in \f$O(nlogn)\f$ time. + * @author [Swastika Gupta](https://github.com/swastyy) + */ + +#include /// for assert +#include /// for std::is_sorted, std::swap +#include /// for io operations +#include /// for std::vector + +/** + * @namespace sorting + * @brief Sorting algorithms + */ +namespace sorting { +/** + * @namespace wave_sort + * @brief Functions for [Wave sort] algorithm + */ +namespace wave_sort { +/** + * @brief The main function implements waveSort + * @tparam T type of array + * @param in_arr array to be sorted + * @returns arr the wave sorted array + */ +template +std::vector waveSort(const std::vector &in_arr) { + std::vector arr(in_arr); + int n = sizeof(in_arr)/sizeof(int); + + for (int i=0;i array1 = {10, 90, 49, 2, 1, 5, 23}; + std::cout << "Test 1... "; + std::vector arr1 = sorting::wave_sort::waveSort(array1); + std::vector o1 = {2, 1, 10, 5, 49, 23, 90}; + assert(std::equal(arr1.begin(),arr1.end(),o1.begin(),o1.end())); + std::cout << "passed" << std::endl; + + // [1, 3, 4, 2, 7, 8] return [2, 1, 4, 3, 8, 7] + std::vector array2 = {1, 3, 4, 2, 7, 8}; + std::cout << "Test 2... "; + std::vector arr2 = sorting::wave_sort::waveSort(array2); + std::vector o2 = {2, 1, 4, 3, 8, 7}; + assert(std::equal(arr2.begin(),arr2.end(),o2.begin(),o2.end())); + std::cout << "passed" << std::endl; + + // [3, 3, 3, 3] return [3, 3, 3, 3] + std::vector array3 = {3, 3, 3, 3}; + std::cout << "Test 3... "; + std::vector arr3 = sorting::wave_sort::waveSort(array3); + std::vector o3 = {3, 3, 3, 3}; + assert(std::equal(arr3.begin(),arr3.end(),o3.begin(),o3.end())); + std::cout << "passed" << std::endl; + + // [9, 4, 6, 8, 14, 3] return [4, 3, 8, 6, 14, 9] + std::vector array4 = {9, 4, 6, 8, 14, 3}; + std::cout << "Test 4... "; + std::vector arr4 = sorting::wave_sort::waveSort(array4); + std::vector o4 = {4, 3, 8, 6, 14, 9}; + assert(std::equal(arr4.begin(),arr4.end(),o4.begin(),o4.end())); + std::cout << "passed" << std::endl; +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + test(); // execute the test + return 0; +}