diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index fcff12b9e..875cc4efa 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: false contact_links: - name: Discord community - url: https://discord.gg/c7MnfGFGa6 + url: https://the-algorithms.com/discord/ about: Have any questions or found any bugs? Please contact us via Discord diff --git a/.github/ISSUE_TEMPLATE/other.yml b/.github/ISSUE_TEMPLATE/other.yml index 901d227ba..d6dc0cfe9 100644 --- a/.github/ISSUE_TEMPLATE/other.yml +++ b/.github/ISSUE_TEMPLATE/other.yml @@ -1,13 +1,10 @@ -name: Other +name: Other issue description: Use this for any other issues. Do NOT create blank issues title: "[OTHER]" -labels: [triage] +labels: ["awaiting triage"] body: - - type: markdown - attributes: - value: "# Other issue" - type: textarea - id: issuedescription + id: description attributes: label: What would you like to share? description: Provide a clear and concise explanation of your issue. diff --git a/.github/workflows/awesome_workflow.yml b/.github/workflows/awesome_workflow.yml index d9b405ec2..315629c98 100644 --- a/.github/workflows/awesome_workflow.yml +++ b/.github/workflows/awesome_workflow.yml @@ -1,51 +1,32 @@ name: Awesome CI Workflow - on: [push, pull_request] -# push: -# branches: [ master ] -# pull_request: -# branches: [ master ] +permissions: + contents: write jobs: MainSequence: name: Code Formatter runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 # v2 is broken for git diff - - uses: actions/setup-python@v2 + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - uses: actions/setup-python@v4 - name: requirements run: | - sudo apt -qq -y update - sudo apt -qq install clang-tidy-10 clang-format-10 + sudo apt-get -qq update + sudo apt-get -qq install clang-tidy clang-format # checks are passing with less errors when used with this version. # The default installs v6.0 which did not work out well in my tests - name: Setup Git Specs run: | - git config --global user.name David Leal - git config --global user.email 'Panquesito7@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git config --global user.name github-actions[bot] + git config --global user.email 'github-actions@users.noreply.github.com' - name: Filename Formatter run: | - IFS=$'\n' - for fname in `find . -type f -name '*.cpp' -o -name '*.cc' -o -name '*.h'` - do - echo "${fname}" - new_fname=`echo ${fname} | tr ' ' '_'` - echo " ${new_fname}" - new_fname=`echo ${new_fname} | tr 'A-Z' 'a-z'` - echo " ${new_fname}" - new_fname=`echo ${new_fname} | tr '-' '_'` - echo " ${new_fname}" - new_fname=${new_fname/.cc/.cpp} - echo " ${new_fname}" - if [ ${fname} != ${new_fname} ] - then - echo " ${fname} --> ${new_fname}" - git "mv" "${fname}" ${new_fname} - fi - done - git commit -am "formatting filenames ${GITHUB_SHA::8}" || true - + wget https://raw.githubusercontent.com/TheAlgorithms/scripts/main/filename_formatter.sh + chmod +x filename_formatter.sh + ./filename_formatter.sh . .cpp,.hpp - name: Update DIRECTORY.md run: | wget https://raw.githubusercontent.com/TheAlgorithms/scripts/main/build_directory_md.py @@ -53,9 +34,7 @@ jobs: git commit -m "updating DIRECTORY.md" DIRECTORY.md || true - name: Get file changes run: | - git remote -v git branch - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY git diff --diff-filter=dr --name-only origin/master > git_diff.txt echo "Files changed-- `cat git_diff.txt`" - name: Configure for static lint checks @@ -81,10 +60,10 @@ jobs: if not cpp_files: sys.exit(0) - subprocess.run(["clang-tidy-10", "--fix", "-p=build", "--extra-arg=-std=c++11", *cpp_files, "--"], + subprocess.run(["clang-tidy", "--fix", "-p=build", "--extra-arg=-std=c++11", *cpp_files, "--"], check=True, text=True, stderr=subprocess.STDOUT) - subprocess.run(["clang-format-10", "-i", "-style=file", *cpp_files], + subprocess.run(["clang-format", "-i", "-style=file", *cpp_files], check=True, text=True, stderr=subprocess.STDOUT) upper_files = [file for file in cpp_files if file != file.lower()] @@ -108,8 +87,8 @@ jobs: - name: Commit and push changes run: | git diff DIRECTORY.md - git commit -am "clang-format and clang-tidy fixes for ${GITHUB_SHA::8}" || true - git push --force origin HEAD:$GITHUB_REF || true + git commit -am "clang-format and clang-tidy fixes for ${GITHUB_SHA::8}" || true + git push origin HEAD:$GITHUB_REF || true build: name: Compile checks @@ -119,7 +98,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] steps: - - uses: actions/checkout@master + - uses: actions/checkout@v3 with: submodules: true - run: cmake -B ./build -S . diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 000000000..c74a015cc --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,51 @@ +name: "CodeQL" + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + steps: + - name: Checkout repository + uses: actions/checkout@v3 + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: cpp + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # â„šī¸ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + # + # In our case, this would be a CMake build step. + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:cpp" diff --git a/.github/workflows/codeql_analysis.yml b/.github/workflows/codeql_analysis.yml deleted file mode 100644 index aa3ddbd7f..000000000 --- a/.github/workflows/codeql_analysis.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: "CodeQL" -on: [push, pull_request] - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - - strategy: - fail-fast: false - matrix: - language: [ 'cpp' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] - # Learn more: - # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed - - steps: - - name: Checkout repository - uses: actions/checkout@main - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@main - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@main - - # â„šī¸ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@main diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 881ea1c33..134c04bb1 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -8,7 +8,7 @@ jobs: build: runs-on: macos-latest steps: - - uses: actions/checkout@master + - uses: actions/checkout@v3 with: submodules: true - name: Install requirements @@ -19,7 +19,7 @@ jobs: - name: build run: cmake --build build -t doc - name: gh-pages - uses: actions/checkout@master + uses: actions/checkout@v3 with: ref: "gh-pages" clean: false diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 406e56b7f..0018600db 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -9,9 +9,9 @@ jobs: - uses: actions/stale@v4 with: stale-issue-message: 'This issue has been automatically marked as abandoned because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' - close-issue-message: 'Please ping one of the maintainers once you add more information and updates here. If this is not the case and you need some help, feel free to ask for help in our [Gitter](https://gitter.im/TheAlgorithms) channel or our [Discord server](https://discord.gg/c7MnfGFGa6). Thank you for your contributions!' + close-issue-message: 'Please ping one of the maintainers once you add more information and updates here. If this is not the case and you need some help, feel free to ask for help in our [Gitter](https://gitter.im/TheAlgorithms) channel or our [Discord server](https://the-algorithms.com/discord/). Thank you for your contributions!' stale-pr-message: 'This pull request has been automatically marked as abandoned because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' - close-pr-message: 'Please ping one of the maintainers once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to ask for help in our [Gitter](https://gitter.im/TheAlgorithms) channel or our [Discord server](https://discord.gg/c7MnfGFGa6). Thank you for your contributions!' + close-pr-message: 'Please ping one of the maintainers once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to ask for help in our [Gitter](https://gitter.im/TheAlgorithms) channel or our [Discord server](https://the-algorithms.com/discord/). Thank you for your contributions!' exempt-issue-labels: 'dont-close,approved' exempt-pr-labels: 'dont-close,approved' days-before-stale: 30 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aa1e6303f..f8f505ae8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ ## Before contributing -Welcome to [TheAlgorithms/C-Plus-Plus](https://github.com/TheAlgorithms/C-Plus-Plus)! Before submitting pull requests, please make sure that you have **read the whole guidelines**. If you have any doubts about this contribution guide, please open [an issue](https://github.com/TheAlgorithms/C-Plus-Plus/issues/new/choose) or ask on our [Discord server](https://discord.gg/c7MnfGFGa6), and clearly state your concerns. +Welcome to [TheAlgorithms/C-Plus-Plus](https://github.com/TheAlgorithms/C-Plus-Plus)! Before submitting pull requests, please make sure that you have **read the whole guidelines**. If you have any doubts about this contribution guide, please open [an issue](https://github.com/TheAlgorithms/C-Plus-Plus/issues/new/choose) or ask on our [Discord server](https://the-algorithms.com/discord/), and clearly state your concerns. ## Contributing @@ -134,7 +134,7 @@ int main(int argc, char *argv[]) { } ``` -#### New File Name guidelines +#### File Name guidelines - Use lowercase words with ``"_"`` as a separator - For instance @@ -148,7 +148,7 @@ my_new_cpp_class.cpp is correct format - File name validation will run on Docker to ensure validity. - If an implementation of the algorithm already exists and your version is different from that implemented, please use incremental numeric digit as a suffix. For example: if `median_search.cpp` already exists in the `search` folder, and you are contributing a new implementation, the filename should be `median_search2.cpp`. For a third implementation, `median_search3.cpp`, and so on. -#### New Directory guidelines +#### Directory guidelines - We recommend adding files to existing directories as much as possible. - Use lowercase words with ``"_"`` as separator ( no spaces or ```"-"``` allowed ) @@ -162,6 +162,40 @@ some_new_fancy_category is correct - Filepaths will be used to dynamically create a directory of our algorithms. - Filepath validation will run on GitHub Actions to ensure compliance. +##### Integrating CMake in a new directory + +In case a new directory is 100% required, `CMakeLists.txt` file in the root directory needs to be updated, and a new `CMakeLists.txt` file needs to be created within the new directory. + +An example of how your new `CMakeLists.txt` file should look like. Note that if there are any extra libraries/setup required, you must include that in this file as well. + +```cmake +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. The RELATIVE flag makes it easier to extract an executable's name +# automatically. + +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +foreach( testsourcefile ${APP_SOURCES} ) + string( REPLACE ".cpp" "" testname ${testsourcefile} ) # File type. Example: `.cpp` + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/") # Folder name. Do NOT include `<>` + +endforeach( testsourcefile ${APP_SOURCES} ) +``` + +The `CMakeLists.txt` file in the root directory should be updated to include the new directory.\ +Include your new directory after the last subdirectory. Example: + +```cmake +... +add_subdirectory(divide_and_conquer) +add_subdirectory() +``` + #### Commit Guidelines - It is recommended to keep your changes grouped logically within individual commits. Maintainers find it easier to understand changes that are logically spilled across multiple commits. Try to modify just one or two files in the same directory. Pull requests that span multiple directories are often rejected. diff --git a/DIRECTORY.md b/DIRECTORY.md index 0752f842d..4fb4b88e1 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -17,6 +17,10 @@ * [Count Bits Flip](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/count_bits_flip.cpp) * [Count Of Set Bits](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/count_of_set_bits.cpp) * [Count Of Trailing Ciphers In Factorial N](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/count_of_trailing_ciphers_in_factorial_n.cpp) +<<<<<<< HEAD +======= + * [Find Non Repeating Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/find_non_repeating_number.cpp) +>>>>>>> 582cdc7cc43c2e6bab2662127485c1965443c8bf * [Hamming Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/hamming_distance.cpp) * [Set Kth Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/set_kth_bit.cpp) diff --git a/README.md b/README.md index 91f62c07b..d3f5f75fb 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,14 @@ [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/C-Plus-Plus) -[![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/TheAlgorithms/C-Plus-Plus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/TheAlgorithms/C-Plus-Plus/context:cpp) -[![CodeQL CI](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql_analysis.yml/badge.svg)](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql_analysis.yml) +[![CodeQL CI](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql.yml/badge.svg)](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql_analysis.yml) [![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms) [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md) ![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) [![Doxygen CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg)](https://TheAlgorithms.github.io/C-Plus-Plus) [![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg)](https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22) [![Income](https://img.shields.io/liberapay/receives/TheAlgorithms.svg?logo=liberapay)](https://liberapay.com/TheAlgorithms) -[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=5865F2)](https://discord.gg/c7MnfGFGa6) +[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=5865F2)](https://the-algorithms.com/discord/) [![Donate](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/TheAlgorithms/donate) ## Overview diff --git a/bit_manipulation/find_non_repeating_number.cpp b/bit_manipulation/find_non_repeating_number.cpp new file mode 100644 index 000000000..cc63d29cc --- /dev/null +++ b/bit_manipulation/find_non_repeating_number.cpp @@ -0,0 +1,88 @@ +/** + * @file + * @brief Implementation to find the non repeating integer + * in an array of repeating integers. [Single + * Number](https://leetcode.com/problems/single-number/) + * + * @details + * Given an array of integers in which all of the numbers occur exactly + * twice except one integer which occurs only once. Find the non-repeating + * integer. + * + * Worst Case Time Complexity: O(n) + * Space complexity: O(1) + + * @author [Ravidev Pandey](https://github.com/literalEval) + */ + +#include /// for assert +#include /// for IO operations +#include /// storing the numbers + +/** + * @namespace bit_manipulation + * @brief Bit manipulation algorithms + */ +namespace bit_manipulation { +/** + * @namespace find_non_repeating_integer + * @brief Functions to find the non repeating integer + * in an array of repeating integers. [Single + * Number](https://leetcode.com/problems/single-number/) + */ +namespace find_non_repeating_integer { +/** + * @brief The main function implements find single number + * @param nums vector of integers + * @returns returns the integer that occurs only once + */ +int64_t find_non_repeating_integer(const std::vector& nums) { + // The idea is based on the property of XOR. + // We know that 'a' XOR 'a' is '0' and '0' XOR 'b' + // is b. + // Using this, if we XOR all the elements of the array, + // the repeating elements will give '0' and this '0' + // with the single number will give the number itself. + + int _xor = 0; + + for (const int& num: nums) { + _xor ^= num; + } + + return _xor; +} +} // namespace find_non_repeating_integer +} // namespace bit_manipulation + +/** + * @brief Self-test implementations + * @returns void + */ +static void test() { + // n = 10,2 return 14 + + std::vector nums_one{1, 1, 2, 2, 4, 5, 5}; + std::vector nums_two{203, 3434, 4545, 3434, 4545}; + std::vector nums_three{90, 1, 3, 90, 3}; + + assert(bit_manipulation::find_non_repeating_integer:: + find_non_repeating_integer(nums_one) == + 4); // 4 is non repeating + assert(bit_manipulation::find_non_repeating_integer:: + find_non_repeating_integer(nums_two) == + 203); // 203 is non repeating + assert(bit_manipulation::find_non_repeating_integer:: + find_non_repeating_integer(nums_three) == + 1); // 1 is non repeating + + std::cout << "All test cases successfully passed!" << std::endl; +} +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + test(); // run self-test implementations + return 0; +} diff --git a/data_structures/stack_using_queue.cpp b/data_structures/stack_using_queue.cpp index bd6a60e2b..b849fcf05 100644 --- a/data_structures/stack_using_queue.cpp +++ b/data_structures/stack_using_queue.cpp @@ -13,7 +13,7 @@ #include /// for queue data structure /** - * @namespace data_strcutres + * @namespace data_structures * @brief Data structures algorithms */ namespace data_structures { diff --git a/graphics/CMakeLists.txt b/graphics/CMakeLists.txt index 2ea6ca230..7a0303707 100644 --- a/graphics/CMakeLists.txt +++ b/graphics/CMakeLists.txt @@ -6,7 +6,7 @@ if(OpenGL_FOUND) include(ExternalProject) ExternalProject_Add ( FREEGLUT-PRJ - URL https://sourceforge.net/projects/freeglut/files/freeglut/3.2.1/freeglut-3.2.1.tar.gz + URL https://github.com/FreeGLUTProject/freeglut/releases/download/v3.2.1/freeglut-3.2.1.tar.gz URL_MD5 cd5c670c1086358598a6d4a9d166949d CMAKE_GENERATOR ${CMAKE_GENERATOR} CMAKE_GENERATOR_TOOLSET ${CMAKE_GENERATOR_TOOLSET} diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index a3b8b0a44..681ab088b 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -16,7 +16,7 @@ where number of pairs line is given by user /** main function */ int main() { int l, st = 2, x, r, z, n, sp; - std::cout << "enter Index "; + std::cout << "Enter number of pair - "; std::cin >> x; z = x; for (r = 1; r <= x; r++) { @@ -26,7 +26,7 @@ int main() { std::cout << " "; } for (l = 1; l <= st; l++) { - std::cout << "*"; + std::cout << "\\*"; } std::cout << std::endl; } diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index ff66b4cf2..514361444 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -1,12 +1,13 @@ /** * @file - * @brief Quick sort algorithm - * - * Implementation Details - - * Quick Sort is a divide and conquer algorithm. It picks and element as - * pivot and partition the given array around the picked pivot. There - * are many different versions of quickSort that pick pivot in different - * ways. + * @brief [Quick sort implementation](https://en.wikipedia.org/wiki/Quicksort) + * in C++ + * @details + * Quick Sort is a [divide and conquer + * algorithm](https://en.wikipedia.org/wiki/Category:Divide-and-conquer_algorithms). + * It picks an element as pivot and partition the given array around the + * picked pivot. There are many different versions of quickSort that pick pivot + * in different ways. * * 1. Always pick the first element as pivot * 2. Always pick the last element as pivot (implemented below) @@ -19,83 +20,219 @@ * than x) before x, and put all greater elements (greater than x) after * x. All this should be done in linear time * + * @author [David Leal](https://github.com/Panquesito7) + * @author [popoapp](https://github.com/popoapp) */ -#include -#include +#include /// for std::is_sorted +#include /// for std::assert +#include /// for std::time +#include /// for IO operations +#include /// for std::vector +/** + * @brief Sorting algorithms + * @namespace sorting + */ namespace sorting { /** - * This function takes last element as pivot, places - * the pivot element at its correct position in sorted - * array, and places all smaller (smaller than pivot) - * to left of pivot and all greater elements to right - * of pivot - * + * @namespace quick_sort + * @brief Functions for the [Quick sort + * implementation](https://en.wikipedia.org/wiki/Quicksort) in C++ */ - -int partition(int arr[], int low, int high) { - int pivot = arr[high]; // taking the last element as pivot - int i = (low - 1); // Index of smaller element +namespace quick_sort { +/** + * @brief Sorts the array taking the last element as pivot + * @details + * This function takes last element as pivot, places + * the pivot element at its correct position in sorted + * array, and places all smaller (smaller than pivot) + * to left of pivot and all greater elements to right of pivot + * @tparam T array type + * @param arr the array with contents given by the user + * @param low first point of the array (starting index) + * @param high last point of the array (ending index) + * @returns index of the smaller element + */ +template +int partition(std::vector *arr, const int &low, const int &high) { + T pivot = (*arr)[high]; // taking the last element as pivot + int i = (low - 1); // Index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot - if (arr[j] <= pivot) { + if ((*arr)[j] <= pivot) { i++; // increment index of smaller element - int temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; + std::swap((*arr)[i], (*arr)[j]); } } - int temp = arr[i + 1]; - arr[i + 1] = arr[high]; - arr[high] = temp; + + std::swap((*arr)[i + 1], (*arr)[high]); return (i + 1); } /** - * The main function that implements QuickSort - * arr[] --> Array to be sorted, - * low --> Starting index, - * high --> Ending index + * @brief the main function that implements Quick Sort. + * + * Void function used in T (array type) function, which then + * can be used as self-tests or other functionalities. + * @tparam T array type + * @param arr array to be sorted + * @param low starting index + * @param high ending index */ -void quickSort(int arr[], int low, int high) { +template +void quick_sort(std::vector *arr, const int &low, const int &high) { if (low < high) { int p = partition(arr, low, high); - quickSort(arr, low, p - 1); - quickSort(arr, p + 1, high); + + quick_sort(arr, low, p - 1); + quick_sort(arr, p + 1, high); } } -} // namespace sorting +/** + * @brief the main function that implements Quick Sort. + * + * T (array type) function which calls the void function. Can + * be used for self-tests and other functionalities. + * @tparam T array type + * @param arr array to be sorted + * @param low starting index + * @param high ending index + */ +template +std::vector quick_sort(std::vector arr, const int &low, const int &high) { + if (low < high) { + int p = partition(&arr, low, high); -using sorting::quickSort; + quick_sort(&arr, low, p - 1); + quick_sort(&arr, p + 1, high); + } + return arr; +} -// prints the array after sorting -void show(int arr[], int size) { +/** + * @brief Utility function to print the array contents + * @param arr the array to be printed + * @param size size of the given array + * @returns void + */ +template +void show(const std::vector &arr, const int &size) { for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } -/** Driver program to test above functions */ -int main() { - int size; - std::cout << "\nEnter the number of elements : "; +} // namespace quick_sort +} // namespace sorting - std::cin >> size; +/** + * @brief Self-test implementations + * @returns void + */ +static void tests() { + // 1st test (normal numbers) + std::vector arr = {5, 3, 8, 12, 14, 16, 28, 96, 2, 5977}; + std::vector arr_sorted = sorting::quick_sort::quick_sort( + arr, 0, int(std::end(arr) - std::begin(arr)) - 1); - int *arr = new int[size]; + assert(std::is_sorted(std::begin(arr_sorted), std::end(arr_sorted))); + std::cout << "\n1st test: passed!\n"; - std::cout << "\nEnter the unsorted elements : "; + // 2nd test (normal and negative numbers) + std::vector arr2 = {9, 15, 28, 96, 500, -4, -58, + -977, -238, -800, -21, -53, -55}; + std::vector arr_sorted2 = sorting::quick_sort::quick_sort( + arr2, 0, std::end(arr2) - std::begin(arr2)); - for (int i = 0; i < size; ++i) { - std::cout << "\n"; - std::cin >> arr[i]; + assert(std::is_sorted(std::begin(arr_sorted2), std::end(arr_sorted2))); + std::cout << "2nd test: passed!\n"; + + // 3rd test (decimal and normal numbers) + std::vector arr3 = {29, 36, 1100, 0, 77, 1, + 6.7, 8.97, 1.74, 950.10, -329.65}; + std::vector arr_sorted3 = sorting::quick_sort::quick_sort( + arr3, 0, int(std::end(arr3) - std::begin(arr3)) - 1); + + assert(std::is_sorted(std::begin(arr_sorted3), std::end(arr_sorted3))); + std::cout << "3rd test: passed!\n"; + + // 4th test (random decimal and negative numbers) + size_t size = std::rand() % 750 + 100; + + std::vector arr4(size); + for (uint64_t i = 0; i < size; i++) { + arr4[i] = static_cast(std::rand()) / + static_cast(RAND_MAX / 999.99 - 0.99) - + 250; + } + + std::vector arr4_sorted = sorting::quick_sort::quick_sort( + arr4, 0, int(std::end(arr4) - std::begin(arr4)) - 1); + assert(std::is_sorted(std::begin(arr4_sorted), std::end(arr4_sorted))); + + std::cout << "4th test: passed!\n"; + + // Printing all sorted arrays + std::cout << "\n\tPrinting all sorted arrays:\t\n"; + + std::cout << "1st array:\n"; + sorting::quick_sort::show(arr_sorted, std::end(arr) - std::begin(arr)); + std::cout << std::endl; + std::cout << "2nd array:\n"; + sorting::quick_sort::show(arr_sorted2, std::end(arr2) - std::begin(arr2)); + std::cout << std::endl; + std::cout << "3rd array:\n"; + sorting::quick_sort::show(arr_sorted3, + int(std::end(arr3) - std::begin(arr3)) - 1); + std::cout << std::endl; + std::cout << "Start: 4th array:\n\n"; + sorting::quick_sort::show( + arr4_sorted, int(std::end(arr4_sorted) - std::begin(arr4_sorted)) - 1); + std::cout << "\nEnd: 4th array.\n"; +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + int choice = 0; + + std::cout << "\tAvailable modes\t\n\n"; + std::cout << "1. Self-tests mode\n2. Interactive mode"; + + std::cout << "\nChoose a mode: "; + std::cin >> choice; + std::cout << "\n"; + + while ((choice != 1) && (choice != 2)) { + std::cout << "Invalid option. Choose between the valid modes: "; + std::cin >> choice; + } + + if (choice == 1) { + std::srand(std::time(nullptr)); + tests(); // run self-test implementations + } else if (choice == 2) { + int size = 0; + std::cout << "\nEnter the number of elements: "; + + std::cin >> size; + std::vector arr(size); + + std::cout + << "\nEnter the unsorted elements (can be negative/decimal): "; + + for (int i = 0; i < size; ++i) { + std::cout << "\n"; + std::cin >> arr[i]; + } + sorting::quick_sort::quick_sort(&arr, 0, size - 1); + std::cout << "\nSorted array: \n"; + sorting::quick_sort::show(arr, size); } - quickSort(arr, 0, size); - std::cout << "Sorted array\n"; - show(arr, size); - delete[] arr; return 0; }