diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml new file mode 100644 index 000000000..11e585dee --- /dev/null +++ b/.github/workflows/awesome_forkflow.yml @@ -0,0 +1,211 @@ +name: Awesome CI Workflow + +on: [push] +# push: +# branches: [ master ] +# pull_request: +# branches: [ master ] + +jobs: + code_format: + name: Code Formatter + runs-on: ubuntu-latest + steps: + - name: requirements + run: | + sudo apt -qq -y update + sudo apt -qq install clang-format + - uses: actions/checkout@master + with: + submodules: true + - name: Setup Git Specs + run: | + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - 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" || true + - name: Clang Formatter + run: | + for fname in $(find . -name '*.cpp' -o -name '*.h') + do + clang-format --verbose -i --style="$line1 $line2 $line3 $line4" "$fname" + done + git commit -am "formatting source-code for $GITHUB_SHA" || true + env: + line1: "{ BasedOnStyle: Google, UseTab: Never," + line2: "IndentWidth: 4, TabWidth: 4, " + line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," + line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" + - name: Git Push + run: git push --force origin HEAD:$GITHUB_REF || true + + update_directory_md: + name: Update Directory.md + needs: code_format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v1 + - name: pull latest commit + run: git pull + - name: Update DIRECTORY.md + shell: python + run: | + import os + from typing import Iterator + + URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" + g_output = [] + + def good_filepaths(top_dir: str = ".") -> Iterator[str]: + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + for dirpath, dirnames, filenames in os.walk(top_dir): + dirnames[:] = [d for d in dirnames if d[0] not in "._"] + for filename in filenames: + if os.path.splitext(filename)[1].lower() in cpp_exts: + yield os.path.join(dirpath, filename).lstrip("./") + + def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + def print_path(old_path: str, new_path: str) -> str: + global g_output + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") + return new_path + + def build_directory_md(top_dir: str = ".") -> str: + global g_output + old_path = "" + for filepath in sorted(good_filepaths(), key=str.lower): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " ").title())[0] + g_output.append(f"{md_prefix(indent)} [{filename}]({url})") + return "# List of all files\n" + "\n".join(g_output) + + with open("DIRECTORY.md", "w") as out_file: + out_file.write(build_directory_md(".") + "\n") + - name: Update DIRECTORY.md + run: | + cat DIRECTORY.md + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add DIRECTORY.md + git commit -am "updating DIRECTORY.md" || true + git push --force origin HEAD:$GITHUB_REF || true + + # cpplint: + # name: CPPLINT + # needs: code_format + # runs-on: ubuntu-latest + # steps: + # - uses: actions/checkout@master + # - uses: actions/setup-python@master + # - run: pip install cpplint + # - run: git pull + # - run: cpplint --filter=-legal --recursive . + + cpplint_modified_files: + runs-on: ubuntu-latest + needs: code_format + name: CPPLINT + steps: + - uses: actions/checkout@master # v2 is broken for git diff + - uses: actions/setup-python@master + - run: python -m pip install cpplint + - run: git remote -v + - run: git branch + - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - run: git pull + - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt + - run: echo "Files changed-- `cat diff.txt`" + - name: cpplint_modified_files + shell: python + run: | + import os + import subprocess + import sys + + print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 + with open("git_diff.txt") as in_file: + modified_files = sorted(in_file.read().splitlines()) + print("{} files were modified.".format(len(modified_files))) + + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] + print(f"{len(cpp_files)} C++ files were modified.") + if not cpp_files: + sys.exit(0) + + print("cpplint:") + for cpp_file in cpp_files: + subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) + + print("g++:") + # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) + # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] + for cpp_file in cpp_files: + subprocess.run(["g++", cpp_file], check=True, text=True) + + upper_files = [file for file in cpp_files if file != file.lower()] + if upper_files: + print(f"{len(upper_files)} files contain uppercase characters:") + print("\n".join(upper_files) + "\n") + + space_files = [file for file in cpp_files if " " in file or "-" in file] + if space_files: + print(f"{len(space_files)} files contain space or dash characters:") + print("\n".join(space_files) + "\n") + + nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] + if nodir_files: + print(f"{len(nodir_files)} files are not in one and only one directory:") + print("\n".join(nodir_files) + "\n") + + bad_files = len(upper_files + space_files + nodir_files) + if bad_files: + sys.exit(bad_files) + + build: + name: Compile checks + runs-on: ${{ matrix.os }} + # needs: [cpplint, update_directory_md, cpplint_modified_files] + needs: [update_directory_md] + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + steps: + - uses: actions/checkout@master + with: + submodules: true + - run: git pull + - run: cmake -B ./build -S . + - run: cmake --build build diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml deleted file mode 100644 index 34085cdec..000000000 --- a/.github/workflows/ccpp.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: C/C++ CI - -on: [push] -# push: -# branches: [ master ] -# pull_request: -# branches: [ master ] - -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] - - steps: - - uses: actions/checkout@master - with: - submodules: true - - name: configure - run: cmake -B ./build -S . - - name: build - run: cmake --build build diff --git a/.github/workflows/cpplint.yml b/.github/workflows/cpplint.yml deleted file mode 100644 index a6999e1f2..000000000 --- a/.github/workflows/cpplint.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: cpplint -on: [push, pull_request] -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 - - run: pip install cpplint - # - run: cpplint --filter= # print out all cpplint rules - - run: cpplint --recursive . || true # all issues to be fixed - # TODO: Remove each filter one at a time and fix those failures - - run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml deleted file mode 100644 index a5aa6a652..000000000 --- a/.github/workflows/cpplint_modified_files.yml +++ /dev/null @@ -1,66 +0,0 @@ -# GitHub Action that enables a repo to achieve gradual compliance with cpplint by -# linting only those files that have been added or modified (vs. origin/master). -# 1. runs cpplint only on those files that have been modified vs. origin/master. -# 2. compiles with g++ only those files that have been modified vs. origin/master. -# 3. other optional filepath verifications may be commented out at the end of this file. -# From: https://github.com/cpplint/GitHub-Action-for-cpplint - -name: cpplint_modified_files -on: [push, pull_request] -jobs: - cpplint_modified_files: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 # v2 is broken for git diff - - uses: actions/setup-python@v1 - - run: python -m pip install cpplint - - run: git remote -v - - run: git branch - - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt - - name: cpplint_modified_files - shell: python - run: | - import os - import subprocess - import sys - - print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 - with open("git_diff.txt") as in_file: - modified_files = sorted(in_file.read().splitlines()) - print("{} files were modified.".format(len(modified_files))) - - cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) - cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] - print(f"{len(cpp_files)} C++ files were modified.") - if not cpp_files: - sys.exit(0) - - print("cpplint:") - for cpp_file in cpp_files: - subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) - - print("g++:") - # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) - # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] - for cpp_file in cpp_files: - subprocess.run(["g++", cpp_file], check=True, text=True) - - upper_files = [file for file in cpp_files if file != file.lower()] - if upper_files: - print(f"{len(upper_files)} files contain uppercase characters:") - print("\n".join(upper_files) + "\n") - - space_files = [file for file in cpp_files if " " in file or "-" in file] - if space_files: - print(f"{len(space_files)} files contain space or dash characters:") - print("\n".join(space_files) + "\n") - - nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] - if nodir_files: - print(f"{len(nodir_files)} files are not in one and only one directory:") - print("\n".join(nodir_files) + "\n") - - bad_files = len(upper_files + space_files + nodir_files) - if bad_files: - sys.exit(bad_files) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml deleted file mode 100644 index 1d63374b0..000000000 --- a/.github/workflows/update_directory_md.yml +++ /dev/null @@ -1,68 +0,0 @@ -# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push -name: update_directory_md -on: [push] -jobs: - update_directory_md: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v1 - - name: update_directory_md - shell: python - run: | - import os - from typing import Iterator - - URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" - g_output = [] - - - def good_filepaths(top_dir: str = ".") -> Iterator[str]: - cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) - for dirpath, dirnames, filenames in os.walk(top_dir): - dirnames[:] = [d for d in dirnames if d[0] not in "._"] - for filename in filenames: - if os.path.splitext(filename)[1].lower() in cpp_exts: - yield os.path.join(dirpath, filename).lstrip("./") - - - def md_prefix(i): - return f"{i * ' '}*" if i else "\n##" - - - def print_path(old_path: str, new_path: str) -> str: - global g_output - old_parts = old_path.split(os.sep) - for i, new_part in enumerate(new_path.split(os.sep)): - if i + 1 > len(old_parts) or old_parts[i] != new_part: - if new_part: - g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") - return new_path - - - def build_directory_md(top_dir: str = ".") -> str: - global g_output - old_path = "" - for filepath in sorted(good_filepaths(), key=str.lower): - filepath, filename = os.path.split(filepath) - if filepath != old_path: - old_path = print_path(old_path, filepath) - indent = (filepath.count(os.sep) + 1) if filepath else 0 - url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") - filename = os.path.splitext(filename.replace("_", " ").title())[0] - g_output.append(f"{md_prefix(indent)} [{filename}]({url})") - return "\n".join(g_output) - - - with open("DIRECTORY.md", "w") as out_file: - out_file.write(build_directory_md(".") + "\n") - - - name: Update DIRECTORY.md - run: | - cat DIRECTORY.md - git config --global user.name github-actions - git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - git add DIRECTORY.md - git commit -am "updating DIRECTORY.md" || true - git push --force origin HEAD:$GITHUB_REF || true diff --git a/DIRECTORY.md b/DIRECTORY.md index 189d6041b..21f1a0c61 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,3 +1,4 @@ +# List of all files ## Backtracking * [Graph Coloring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/graph_coloring.cpp) @@ -18,10 +19,10 @@ * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.cpp) ## Data Structure - * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/AVLtree.cpp) - * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binary%20Search%20Tree.cpp) - * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binaryheap.cpp) - * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) + * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/avltree.cpp) + * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binary_search_tree.cpp) + * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binaryheap.cpp) + * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_queue_using_linked_list.cpp) * Cll * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp) * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h) @@ -29,73 +30,73 @@ * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp) * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/doubly_linked_list.cpp) * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linked_list.cpp) - * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) - * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) - * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) - * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array.cpp) - * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp) + * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedlist_implentation_usingarray.cpp) + * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/list_array.cpp) + * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/morrisinorder.cpp) * Queue * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp) + * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array2.cpp) + * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linked_list.cpp) * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linkedlist.cpp) - * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) - * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) + * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_array.cpp) + * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_linked_list.cpp) * Stk * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/main.cpp) * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.cpp) * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h) * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp) - * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp) + * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/tree.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) ## Dynamic Programming - * [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp) + * [0 1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0_1_knapsack.cpp) * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/armstrong_number.cpp) - * [Bellman-Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Bellman-Ford.cpp) - * [Catalan-Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Catalan-Numbers.cpp) - * [Coin-Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Coin-Change.cpp) - * [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Cut%20Rod.cpp) - * [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Edit%20Distance.cpp) - * [Egg-Dropping-Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Egg-Dropping-Puzzle.cpp) - * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Bottom_Up.cpp) - * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Top_Down.cpp) - * [Floyd-Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Floyd-Warshall.cpp) + * [Bellman Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/bellman_ford.cpp) + * [Catalan Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/catalan_numbers.cpp) + * [Coin Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/coin_change.cpp) + * [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/cut_rod.cpp) + * [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/edit_distance.cpp) + * [Egg Dropping Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/egg_dropping_puzzle.cpp) + * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/fibonacci_bottom_up.cpp) + * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/fibonacci_top_down.cpp) + * [Floyd Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/floyd_warshall.cpp) * [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp) - * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Common%20Subsequence.cpp) - * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence%20(nlogn).cpp) - * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) - * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) + * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_subsequence.cpp) + * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_increasing_subsequence.cpp) + * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp) + * [Matrix Chain Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/matrix_chain_multiplication.cpp) * [Searching Of Element In Dynamic Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/searching_of_element_in_dynamic_array.cpp) * [Tree Height](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/tree_height.cpp) ## Graph - * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/BFS.cpp) + * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bfs.cpp) * [Bridge Finding With Tarjan Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bridge_finding_with_tarjan_algorithm.cpp) * [Connected Components](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components.cpp) * [Connected Components With Dsu](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components_with_dsu.cpp) - * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS.cpp) - * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc) - * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Dijkstra.cpp) + * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs.cpp) + * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs_with_stack.cpp) + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dijkstra.cpp) * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) - * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Kruskal.cpp) + * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kruskal.cpp) * [Lca](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lca.cpp) * [Max Flow With Ford Fulkerson And Edmond Karp Algo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp) * [Prim](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/prim.cpp) - * [Topological-Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Topological-Sort.cpp) + * [Topological Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/topological_sort.cpp) * [Topological Sort By Kahns Algo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/topological_sort_by_kahns_algo.cpp) ## Greedy Algorithms - * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Dijkstra.cpp) + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/dijkstra.cpp) * [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/huffman.cpp) - * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Knapsack.cpp) - * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Kruskals%20Minimum%20Spanning%20Tree.cpp) - * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Prims%20Minimum%20Spanning%20Tree.cpp) + * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/knapsack.cpp) + * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/kruskals_minimum_spanning_tree.cpp) + * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/prims_minimum_spanning_tree.cpp) ## Hashing - * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/Chaining.cpp) + * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/chaining.cpp) * [Double Hash Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/double_hash_hash_table.cpp) * [Linear Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/linear_probing_hash_table.cpp) * [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp) @@ -126,15 +127,15 @@ * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/string_fibonacci.cpp) ## Operations On Datastructures - * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Left%20Rotation.cpp) - * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Right%20Rotation.cpp) - * [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Linked%20List.cpp) - * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Queue%20Using%20Array.cpp) + * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_left_rotation.cpp) + * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_right_rotation.cpp) + * [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/circular_linked_list.cpp) + * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/circular_queue_using_array.cpp) * [Get Size Of Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/get_size_of_linked_list.cpp) - * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Intersection_of_2_arrays.cpp) - * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Reverse%20a%20Linked%20List%20using%20Recusion.cpp) - * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionSortLinkedList.cpp) - * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp) + * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/intersection_of_2_arrays.cpp) + * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp) + * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionsortlinkedlist.cpp) + * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/union_of_2_arrays.cpp) ## Others * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/buzz_number.cpp) @@ -163,9 +164,9 @@ ## Range Queries * [Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/bit.cpp) - * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/FenwickTree.cpp) - * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/MO.cpp) - * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segTree.cpp) + * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/fenwicktree.cpp) + * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/mo.cpp) + * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segtree.cpp) ## Search * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/binary_search.cpp) @@ -186,7 +187,7 @@ * [Bucket Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucket_sort.cpp) * [Cocktail Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/cocktail_selection_sort.cpp) * [Comb Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/comb_sort.cpp) - * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) + * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort.cpp) * [Counting Sort String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort_string.cpp) * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/insertion_sort.cpp) diff --git a/backtracking/graph_coloring.cpp b/backtracking/graph_coloring.cpp index cadc6d5ec..19a983019 100644 --- a/backtracking/graph_coloring.cpp +++ b/backtracking/graph_coloring.cpp @@ -7,8 +7,7 @@ void printSolution(int color[]); /* A utility function to check if the current color assignment is safe for vertex v */ -bool isSafe(int v, bool graph[V][V], int color[], int c) -{ +bool isSafe(int v, bool graph[V][V], int color[], int c) { for (int i = 0; i < V; i++) if (graph[v][i] && c == color[i]) return false; @@ -16,22 +15,18 @@ bool isSafe(int v, bool graph[V][V], int color[], int c) } /* A recursive utility function to solve m coloring problem */ -void graphColoring(bool graph[V][V], int m, int color[], int v) -{ +void graphColoring(bool graph[V][V], int m, int color[], int v) { /* base case: If all vertices are assigned a color then return true */ - if (v == V) - { + if (v == V) { printSolution(color); return; } /* Consider this vertex v and try different colors */ - for (int c = 1; c <= m; c++) - { + for (int c = 1; c <= m; c++) { /* Check if assignment of color c to v is fine*/ - if (isSafe(v, graph, color, c)) - { + if (isSafe(v, graph, color, c)) { color[v] = c; /* recur to assign colors to rest of the vertices */ @@ -45,17 +40,14 @@ void graphColoring(bool graph[V][V], int m, int color[], int v) } /* A utility function to print solution */ -void printSolution(int color[]) -{ +void printSolution(int color[]) { printf(" Following are the assigned colors \n"); - for (int i = 0; i < V; i++) - printf(" %d ", color[i]); + for (int i = 0; i < V; i++) printf(" %d ", color[i]); printf("\n"); } // driver program to test above function -int main() -{ +int main() { /* Create following graph and test whether it is 3 colorable (3)---(2) | / | @@ -69,12 +61,11 @@ int main() {1, 1, 0, 1}, {1, 0, 1, 0}, }; - int m = 3; // Number of colors + int m = 3; // Number of colors int color[V]; - for (int i = 0; i < V; i++) - color[i] = 0; + for (int i = 0; i < V; i++) color[i] = 0; graphColoring(graph, m, color, 0); return 0; diff --git a/backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp index fbb8a6f96..c97523be7 100644 --- a/backtracking/knight_tour.cpp +++ b/backtracking/knight_tour.cpp @@ -1,68 +1,60 @@ #include -# define n 8 +#define n 8 /** A knight's tour is a sequence of moves of a knight on a chessboard -such that the knight visits every square only once. If the knight -ends on a square that is one knight's move from the beginning -square (so that it could tour the board again immediately, following +such that the knight visits every square only once. If the knight +ends on a square that is one knight's move from the beginning +square (so that it could tour the board again immediately, following the same path), the tour is closed; otherwise, it is open. **/ -using namespace std; -bool issafe(int x,int y,int sol[n][n]) -{ - return (x=0 && y=0 && sol[x][y]==-1); +using std::cin; +using std::cout; +bool issafe(int x, int y, int sol[n][n]) { + return (x < n && x >= 0 && y < n && y >= 0 && sol[x][y] == -1); } -bool solve(int x,int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) -{ - int k,xnext,ynext; +bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) { + int k, xnext, ynext; - if(mov == n*n) + if (mov == n * n) return true; - for(k=0;k<8;k++) - { - xnext=x+xmov[k]; - ynext=y+ymov[k]; + for (k = 0; k < 8; k++) { + xnext = x + xmov[k]; + ynext = y + ymov[k]; - if(issafe(xnext,ynext,sol)) - { - sol[xnext][ynext]=mov; + if (issafe(xnext, ynext, sol)) { + sol[xnext][ynext] = mov; - if(solve(xnext,ynext,mov+1,sol,xmov,ymov)==true) - return true; - else - sol[xnext][ynext]=-1; - } + if (solve(xnext, ynext, mov + 1, sol, xmov, ymov) == true) + return true; + else + sol[xnext][ynext] = -1; + } } return false; } -int main() -{ - //initialize(); +int main() { + // initialize(); int sol[n][n]; - int i,j; - for(i=0;i scores, } int main() { - vector scores = { 90, 23, 6, 33, 21, 65, 123, 34423 }; + vector scores = {90, 23, 6, 33, 21, 65, 123, 34423}; int height = log2(scores.size()); cout << "Optimal value: " << minimax(0, 0, true, scores, height) << endl; diff --git a/backtracking/n_queens.cpp b/backtracking/n_queens.cpp index 472aaa2fe..8aab5df7b 100644 --- a/backtracking/n_queens.cpp +++ b/backtracking/n_queens.cpp @@ -2,19 +2,15 @@ #define N 4 using namespace std; -void printSolution(int board[N][N]) -{ +void printSolution(int board[N][N]) { cout << "\n"; - for (int i = 0; i < N; i++) - { - for (int j = 0; j < N; j++) - cout << "" << board[i][j]; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) cout << "" << board[i][j]; cout << "\n"; } } -bool isSafe(int board[N][N], int row, int col) -{ +bool isSafe(int board[N][N], int row, int col) { int i, j; /* Check this row on left side */ @@ -35,23 +31,18 @@ bool isSafe(int board[N][N], int row, int col) return true; } -void solveNQ(int board[N][N], int col) -{ - - if (col >= N) - { +void solveNQ(int board[N][N], int col) { + if (col >= N) { printSolution(board); return; } /* Consider this column and try placing this queen in all rows one by one */ - for (int i = 0; i < N; i++) - { + for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ - if (isSafe(board, i, col)) - { + if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ // cout<<"\n"< #define n 4 -#define inc_loop(var, start, stop) for (int var=start; var <= stop; var++) -#define dec_loop(var, start, stop) for (int var=start; var >= stop; var--) +#define inc_loop(var, start, stop) for (int var = start; var <= stop; var++) +#define dec_loop(var, start, stop) for (int var = start; var >= stop; var--) void PrintSol(int Board[n][n]) { - inc_loop(i, 0, n-1) { - inc_loop(j, 0, n-1) - std::cout << Board[i][j] << " "; + inc_loop(i, 0, n - 1) { + inc_loop(j, 0, n - 1) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; - if (n%2 == 0 || (n%2 == 1 && Board[n/2+1][0] != 1)) { - inc_loop(i, 0, n-1) { - dec_loop(j, n-1, 0) - std::cout << Board[i][j] << " "; + if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) { + inc_loop(i, 0, n - 1) { + dec_loop(j, n - 1, 0) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; @@ -21,7 +19,7 @@ void PrintSol(int Board[n][n]) { bool CanIMove(int Board[n][n], int row, int col) { /// check in the row - inc_loop(i, 0, col-1) { + inc_loop(i, 0, col - 1) { if (Board[row][i] == 1) return false; } @@ -43,7 +41,7 @@ void NQueenSol(int Board[n][n], int col) { PrintSol(Board); return; } - inc_loop(i, 0, n-1) { + inc_loop(i, 0, n - 1) { if (CanIMove(Board, i, col)) { Board[i][col] = 1; NQueenSol(Board, col + 1); @@ -54,8 +52,8 @@ void NQueenSol(int Board[n][n], int col) { int main() { int Board[n][n] = {0}; - if (n%2 == 0) { - inc_loop(i, 0, n/2-1) { + if (n % 2 == 0) { + inc_loop(i, 0, n / 2 - 1) { if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); @@ -63,7 +61,7 @@ int main() { } } } else { - inc_loop(i, 0, n/2) { + inc_loop(i, 0, n / 2) { if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); diff --git a/backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp index 307b5c7b0..fb3be4451 100644 --- a/backtracking/rat_maze.cpp +++ b/backtracking/rat_maze.cpp @@ -1,73 +1,62 @@ /* - A Maze is given as N*N binary matrix of blocks where source block is the upper - left most block i.e., maze[0][0] and destination block is lower rightmost - block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. - The rat can move only in two directions: forward and down. In the maze matrix, - 0 means the block is dead end and 1 means the block can be used in the path - from source to destination. + A Maze is given as N*N binary matrix of blocks where source block is the + upper left most block i.e., maze[0][0] and destination block is lower + rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to + reach destination. The rat can move only in two directions: forward and down. + In the maze matrix, 0 means the block is dead end and 1 means the block can + be used in the path from source to destination. */ #include #define size 4 using namespace std; -int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size]) -{ - if ((currposrow == size - 1) && (currposcol == size - 1)) - { - soln[currposrow][currposcol] = 1; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { - cout << soln[i][j]; - } - cout << endl; - } - return 1; - } - else - { - soln[currposrow][currposcol] = 1; +int solveMaze(int currposrow, int currposcol, int maze[size][size], + int soln[size][size]) { + if ((currposrow == size - 1) && (currposcol == size - 1)) { + soln[currposrow][currposcol] = 1; + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { + cout << soln[i][j]; + } + cout << endl; + } + return 1; + } else { + soln[currposrow][currposcol] = 1; - // if there exist a solution by moving one step ahead in a collumn - if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln)) - { - return 1; - } + // if there exist a solution by moving one step ahead in a collumn + if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && + solveMaze(currposrow, currposcol + 1, maze, soln)) { + return 1; + } - // if there exists a solution by moving one step ahead in a row - if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln)) - { - return 1; - } + // if there exists a solution by moving one step ahead in a row + if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && + solveMaze(currposrow + 1, currposcol, maze, soln)) { + return 1; + } - // the backtracking part - soln[currposrow][currposcol] = 0; - return 0; - } + // the backtracking part + soln[currposrow][currposcol] = 0; + return 0; + } } -int main(int argc, char const *argv[]) -{ - int maze[size][size] = { - {1, 0, 1, 0}, - {1, 0, 1, 1}, - {1, 0, 0, 1}, - {1, 1, 1, 1}}; +int main(int argc, char const *argv[]) { + int maze[size][size] = { + {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}; - int soln[size][size]; + int soln[size][size]; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { - soln[i][j] = 0; - } - } + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { + soln[i][j] = 0; + } + } - int currposrow = 0; - int currposcol = 0; - solveMaze(currposrow, currposcol, maze, soln); - return 0; + int currposrow = 0; + int currposcol = 0; + solveMaze(currposrow, currposcol, maze, soln); + return 0; } diff --git a/backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp index 6a01fd395..b712b6ec7 100644 --- a/backtracking/sudoku_solve.cpp +++ b/backtracking/sudoku_solve.cpp @@ -1,15 +1,12 @@ #include using namespace std; -///N=9; +/// N=9; int n = 9; -bool isPossible(int mat[][9], int i, int j, int no) -{ - ///Row or col nahin hona chahiye - for (int x = 0; x < n; x++) - { - if (mat[x][j] == no || mat[i][x] == no) - { +bool isPossible(int mat[][9], int i, int j, int no) { + /// Row or col nahin hona chahiye + for (int x = 0; x < n; x++) { + if (mat[x][j] == no || mat[i][x] == no) { return false; } } @@ -18,12 +15,9 @@ bool isPossible(int mat[][9], int i, int j, int no) int sx = (i / 3) * 3; int sy = (j / 3) * 3; - for (int x = sx; x < sx + 3; x++) - { - for (int y = sy; y < sy + 3; y++) - { - if (mat[x][y] == no) - { + for (int x = sx; x < sx + 3; x++) { + for (int y = sy; y < sy + 3; y++) { + if (mat[x][y] == no) { return false; } } @@ -31,83 +25,63 @@ bool isPossible(int mat[][9], int i, int j, int no) return true; } -void printMat(int mat[][9]) -{ - - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { +void printMat(int mat[][9]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { cout << mat[i][j] << " "; - if ((j + 1) % 3 == 0) - { + if ((j + 1) % 3 == 0) { cout << '\t'; } } - if ((i + 1) % 3 == 0) - { + if ((i + 1) % 3 == 0) { cout << endl; } cout << endl; } } -bool solveSudoku(int mat[][9], int i, int j) -{ - ///Base Case - if (i == 9) - { - ///Solve kr chuke hain for 9 rows already +bool solveSudoku(int mat[][9], int i, int j) { + /// Base Case + if (i == 9) { + /// Solve kr chuke hain for 9 rows already printMat(mat); return true; } - ///Crossed the last Cell in the row - if (j == 9) - { + /// Crossed the last Cell in the row + if (j == 9) { return solveSudoku(mat, i + 1, 0); } - ///Blue Cell - Skip - if (mat[i][j] != 0) - { + /// Blue Cell - Skip + if (mat[i][j] != 0) { return solveSudoku(mat, i, j + 1); } - ///White Cell - ///Try to place every possible no - for (int no = 1; no <= 9; no++) - { - if (isPossible(mat, i, j, no)) - { - ///Place the no - assuming solution aa jayega + /// White Cell + /// Try to place every possible no + for (int no = 1; no <= 9; no++) { + if (isPossible(mat, i, j, no)) { + /// Place the no - assuming solution aa jayega mat[i][j] = no; bool aageKiSolveHui = solveSudoku(mat, i, j + 1); - if (aageKiSolveHui) - { + if (aageKiSolveHui) { return true; } - ///Nahin solve hui - ///loop will place the next no. + /// Nahin solve hui + /// loop will place the next no. } } - ///Sare no try kr liey, kisi se bhi solve nahi hui + /// Sare no try kr liey, kisi se bhi solve nahi hui mat[i][j] = 0; return false; } -int main() -{ - - int mat[9][9] = - {{5, 3, 0, 0, 7, 0, 0, 0, 0}, - {6, 0, 0, 1, 9, 5, 0, 0, 0}, - {0, 9, 8, 0, 0, 0, 0, 6, 0}, - {8, 0, 0, 0, 6, 0, 0, 0, 3}, - {4, 0, 0, 8, 0, 3, 0, 0, 1}, - {7, 0, 0, 0, 2, 0, 0, 0, 6}, - {0, 6, 0, 0, 0, 0, 2, 8, 0}, - {0, 0, 0, 4, 1, 9, 0, 0, 5}, - {0, 0, 0, 0, 8, 0, 0, 7, 9}}; +int main() { + int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, + {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, + {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, + {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, + {0, 0, 0, 0, 8, 0, 0, 7, 9}}; printMat(mat); cout << "Solution " << endl; diff --git a/data_structure/AVLtree.cpp b/data_structure/AVLtree.cpp deleted file mode 100644 index db6b9e0d4..000000000 --- a/data_structure/AVLtree.cpp +++ /dev/null @@ -1,176 +0,0 @@ -#include -#include - -using namespace std; - -typedef struct node -{ - int data; - int height; - struct node *left; - struct node *right; -} node; - -int max(int a, int b) -{ - return a > b ? a : b; -} - -// Returns a new Node - -node *createNode(int data) -{ - node *nn = new node(); - nn->data = data; - nn->height = 0; - nn->left = NULL; - nn->right = NULL; - return nn; -} - -// Returns height of tree - -int height(node *root) -{ - if (root == NULL) - return 0; - return 1 + max(height(root->left), height(root->right)); -} - -// Returns difference between height of left and right subtree - -int getBalance(node *root) -{ - return height(root->left) - height(root->right); -} - -// Returns Node after Right Rotation - -node *rightRotate(node *root) -{ - node *t = root->left; - node *u = t->right; - t->right = root; - root->left = u; - return t; -} - -// Returns Node after Left Rotation - -node *leftRotate(node *root) -{ - node *t = root->right; - node *u = t->left; - t->left = root; - root->right = u; - return t; -} - -// Returns node with minimum value in the tree - -node *minValue(node *root) -{ - if (root->left == NULL) - return root; - return minValue(root->left); -} - -// Balanced Insertion - -node *insert(node *root, int item) -{ - node *nn = createNode(item); - if (root == NULL) - return nn; - if (item < root->data) - root->left = insert(root->left, item); - else - root->right = insert(root->right, item); - int b = getBalance(root); - if (b > 1) - { - if (getBalance(root->left) < 0) - root->left = leftRotate(root->left); // Left-Right Case - return rightRotate(root); // Left-Left Case - } - else if (b < -1) - { - if (getBalance(root->right) > 0) - root->right = rightRotate(root->right); // Right-Left Case - return leftRotate(root); // Right-Right Case - } - return root; -} - -// Balanced Deletion - -node *deleteNode(node *root, int key) -{ - if (root == NULL) - return root; - if (key < root->data) - root->left = deleteNode(root->left, key); - else if (key > root->data) - root->right = deleteNode(root->right, key); - - else - { - // Node to be deleted is leaf node or have only one Child - if (!root->right) - { - node *temp = root->left; - delete (root); - root = NULL; - return temp; - } - else if (!root->left) - { - node *temp = root->right; - delete (root); - root = NULL; - return temp; - } - // Node to be deleted have both left and right subtrees - node *temp = minValue(root->right); - root->data = temp->data; - root->right = deleteNode(root->right, temp->data); - } - // Balancing Tree after deletion - return root; -} - -// LevelOrder (Breadth First Search) - -void levelOrder(node *root) -{ - queue q; - q.push(root); - while (!q.empty()) - { - root = q.front(); - cout << root->data << " "; - q.pop(); - if (root->left) - q.push(root->left); - if (root->right) - q.push(root->right); - } -} - -int main() -{ - // Testing AVL Tree - node *root = NULL; - int i; - for (i = 1; i <= 7; i++) - root = insert(root, i); - cout << "LevelOrder: "; - levelOrder(root); - root = deleteNode(root, 1); // Deleting key with value 1 - cout << "\nLevelOrder: "; - levelOrder(root); - root = deleteNode(root, 4); // Deletin key with value 4 - cout << "\nLevelOrder: "; - levelOrder(root); - return 0; -} diff --git a/data_structure/Binary Search Tree.cpp b/data_structure/Binary Search Tree.cpp deleted file mode 100644 index 32a65517c..000000000 --- a/data_structure/Binary Search Tree.cpp +++ /dev/null @@ -1,218 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *left; - node *right; -}; - -struct queue -{ - node *t[100]; - int front; - int rear; -}; - -queue q; - -void enqueue(node *n) -{ - q.t[q.rear++] = n; -} - -node *dequeue() -{ - return (q.t[q.front++]); -} - -void Insert(node *n, int x) -{ - if (x < n->val) - { - if (n->left == NULL) - { - node *temp = new node; - temp->val = x; - temp->left = NULL; - temp->right = NULL; - n->left = temp; - } - else - { - Insert(n->left, x); - } - } - else - { - if (n->right == NULL) - { - node *temp = new node; - temp->val = x; - temp->left = NULL; - temp->right = NULL; - n->left = temp; - } - else - { - Insert(n->right, x); - } - } -} - -int findMaxInLeftST(node *n) -{ - while (n->right != NULL) - { - n = n->right; - } - return n->val; -} - -void Remove(node *p, node *n, int x) -{ - if (n->val == x) - { - if (n->right == NULL && n->left == NULL) - { - if (x < p->val) - { - p->right = NULL; - } - else - { - p->left = NULL; - } - } - else if (n->right == NULL) - { - if (x < p->val) - { - p->right = n->left; - } - else - { - p->left = n->left; - } - } - else if (n->left == NULL) - { - if (x < p->val) - { - p->right = n->right; - } - else - { - p->left = n->right; - } - } - else - { - int y = findMaxInLeftST(n->left); - n->val = y; - Remove(n, n->right, y); - } - } - else if (x < n->val) - { - Remove(n, n->left, x); - } - else - { - Remove(n, n->right, x); - } -} - -void BFT(node *n) -{ - if (n != NULL) - { - cout << n->val << " "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } -} - -void Pre(node *n) -{ - if (n != NULL) - { - cout << n->val << " "; - Pre(n->left); - Pre(n->right); - } -} - -void In(node *n) -{ - if (n != NULL) - { - In(n->left); - cout << n->val << " "; - In(n->right); - } -} - -void Post(node *n) -{ - if (n != NULL) - { - Post(n->left); - Post(n->right); - cout << n->val << " "; - } -} - -int main() -{ - q.front = 0; - q.rear = 0; - int value; - int ch; - node *root = new node; - cout << "\nEnter the value of root node :"; - cin >> value; - root->val = value; - root->left = NULL; - root->right = NULL; - do - { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Breadth First"; - cout << "\n4. Preorder Depth First"; - cout << "\n5. Inorder Depth First"; - cout << "\n6. Postorder Depth First"; - - cout << "\nEnter Your Choice : "; - cin >> ch; - int x; - switch (ch) - { - case 1: - cout << "\nEnter the value to be Inserted : "; - cin >> x; - Insert(root, x); - break; - case 2: - cout << "\nEnter the value to be Deleted : "; - cin >> x; - Remove(root, root, x); - break; - case 3: - BFT(root); - break; - case 4: - Pre(root); - break; - case 5: - In(root); - break; - case 6: - Post(root); - break; - } - } while (ch != 0); -} diff --git a/data_structure/List Array.cpp b/data_structure/List Array.cpp deleted file mode 100644 index de984876b..000000000 --- a/data_structure/List Array.cpp +++ /dev/null @@ -1,188 +0,0 @@ -#include -using namespace std; - -struct list -{ - int data[50]; - int top = 0; - bool isSorted = false; - - int BinarySearch(int *array, int first, int last, int x) - { - if (last < first) - { - return -1; - } - int mid = (first + last) / 2; - if (array[mid] == x) - return mid; - else if (x < array[mid]) - return (BinarySearch(array, first, mid - 1, x)); - else if (x > array[mid]) - return (BinarySearch(array, mid + 1, last, x)); - } - - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i] == x) - { - return i; - } - } - - return -1; - } - - int Search(int x) - { - int pos = -1; - - if (isSorted) - { - pos = BinarySearch(data, 0, top - 1, x); - } - - else - { - pos = LinarSearch(data, x); - } - - if (pos != -1) - { - cout << "\nElement found at position : " << pos; - } - else - { - cout << "\nElement not found"; - } - return pos; - } - - void Sort() - { - int i, j, pos; - for (i = 0; i < top; i++) - { - int min = data[i]; - for (j = i + 1; j < top; j++) - { - if (data[j] < min) - { - pos = j; - min = data[pos]; - } - } - - int temp = data[i]; - data[i] = data[pos]; - data[pos] = temp; - } - isSorted = true; - } - - void insert(int x) - { - if (!isSorted) - { - - if (top == 49) - { - cout << "\nOverflow"; - } - else - { - data[top] = x; - top++; - } - } - - else - { - int pos = 0; - - for (int i = 0; i < top - 1; i++) - { - if (data[i] <= x && x <= data[i + 1]) - { - pos = i + 1; - break; - } - } - if (pos == 0) - { - pos = top - 1; - } - - for (int i = top; i > pos; i--) - { - data[i] = data[i - 1]; - } - top++; - data[pos] = x; - } - } - - void Remove(int x) - { - int pos = Search(x); - cout << "\n" - << data[pos] << " deleted"; - for (int i = pos; i < top; i++) - { - data[i] = data[i + 1]; - } - top--; - } - - void Show() - { - for (int i = 0; i < top; i++) - { - cout << data[i] << "\t"; - } - } -}; - -int main() -{ - list L; - int choice; - int x; - do - { - cout << "\n1.Insert"; - cout << "\n2.Delete"; - cout << "\n3.Search"; - cout << "\n4.Sort"; - cout << "\n5.Print"; - cout << "\n\nEnter Your Choice : "; - cin >> choice; - switch (choice) - { - case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; - L.insert(x); - break; - case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; - L.Remove(x); - break; - case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; - L.Search(x); - break; - case 4: - L.Sort(); - break; - case 5: - L.Show(); - break; - } - } while (choice != 0); - return 0; -} diff --git a/data_structure/MorrisInorder.cpp b/data_structure/MorrisInorder.cpp deleted file mode 100644 index d3a2e9fd7..000000000 --- a/data_structure/MorrisInorder.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include -#include - -/************************** - @author shrutisheoran -**************************/ - -using namespace std; - -struct Btree -{ - int data; - struct Btree *left; //Pointer to left subtree - struct Btree *right; //Pointer to right subtree -}; - -void insert(Btree **root, int d) -{ - Btree *nn = new Btree(); //Creating new node - nn->data = d; - nn->left = NULL; - nn->right = NULL; - if (*root == NULL) - { - *root = nn; - return; - } - else - { - queue q; - // Adding root node to queue - q.push(*root); - while (!q.empty()) - { - Btree *node = q.front(); - // Removing parent node from queue - q.pop(); - if (node->left) - // Adding left child of removed node to queue - q.push(node->left); - else - { - // Adding new node if no left child is present - node->left = nn; - return; - } - if (node->right) - // Adding right child of removed node to queue - q.push(node->right); - else - { - // Adding new node if no right child is present - node->right = nn; - return; - } - } - } -} - -void morrisInorder(Btree *root) -{ - Btree *curr = root; - Btree *temp; - while (curr) - { - if (curr->left == NULL) - { - cout << curr->data << " "; - // If left of current node is NULL then curr is shifted to right - curr = curr->right; - } - else - { - // Left of current node is stored in temp - temp = curr->left; - // Moving to extreme right of temp - while (temp->right && temp->right != curr) - temp = temp->right; - // If extreme right is null it is made to point to currrent node (will be used for backtracking) - if (temp->right == NULL) - { - temp->right = curr; - // current node is made to point its left subtree - curr = curr->left; - } - // If extreme right already points to currrent node it it set to null - else if (temp->right == curr) - { - cout << curr->data << " "; - temp->right = NULL; - // current node is made to point its right subtree - curr = curr->right; - } - } - } -} - -int main() -{ - // Testing morrisInorder funtion - Btree *root = NULL; - int i; - for (i = 1; i <= 7; i++) - insert(&root, i); - cout << "Morris Inorder: "; - morrisInorder(root); - return 0; -} diff --git a/data_structure/Queue Using Array.cpp b/data_structure/Queue Using Array.cpp deleted file mode 100644 index 3b79d06fc..000000000 --- a/data_structure/Queue Using Array.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include -using namespace std; - -int queue[10]; -int front = 0; -int rear = 0; - -void Enque(int x) -{ - if (rear == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear++] = x; - } -} - -void Deque() -{ - if (front == rear) - { - cout << "\nUnderflow"; - } - - else - { - cout << "\n" - << queue[front++] << " deleted"; - for (int i = front; i < rear; i++) - { - queue[i - front] = queue[i]; - } - rear = rear - front; - front = 0; - } -} - -void show() -{ - for (int i = front; i < rear; i++) - { - cout << queue[i] << "\t"; - } -} - -int main() -{ - int ch, x; - do - { - cout << "\n1. Enque"; - cout << "\n2. Deque"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - Enque(x); - } - else if (ch == 2) - { - Deque(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); - - return 0; -} diff --git a/data_structure/Stack Using Array.cpp b/data_structure/Stack Using Array.cpp deleted file mode 100644 index af1d57c46..000000000 --- a/data_structure/Stack Using Array.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include -using namespace std; - -int *stack; -int top = 0, size; - -void push(int x) -{ - if (top == size) - { - cout << "\nOverflow"; - } - else - { - stack[top++] = x; - } -} - -void pop() -{ - if (top == 0) - { - cout << "\nUnderflow"; - } - else - { - cout << "\n" - << stack[--top] << " deleted"; - } -} - -void show() -{ - for (int i = 0; i < top; i++) - { - cout << stack[i] << "\n"; - } -} - -void topmost() -{ - cout << "\nTopmost element: " << stack[top - 1]; -} -int main() -{ - cout << "\nEnter Size of stack : "; - cin >> size; - stack = new int[size]; - int ch, x; - do - { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\n4. Print topmost element:"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - push(x); - } - else if (ch == 2) - { - pop(); - } - else if (ch == 3) - { - show(); - } - else if (ch == 4) - { - topmost(); - } - } while (ch != 0); - - return 0; -} diff --git a/data_structure/Stack Using Linked List.cpp b/data_structure/Stack Using Linked List.cpp deleted file mode 100644 index 6925cf10c..000000000 --- a/data_structure/Stack Using Linked List.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - -node *top; - -void push(int x) -{ - node *n = new node; - n->val = x; - n->next = top; - top = n; -} - -void pop() -{ - if (top == NULL) - { - cout << "\nUnderflow"; - } - else - { - node *t = top; - cout << "\n" - << t->val << " deleted"; - top = top->next; - delete t; - } -} - -void show() -{ - node *t = top; - while (t != NULL) - { - cout << t->val << "\n"; - t = t->next; - } -} - -int main() -{ - int ch, x; - do - { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - push(x); - } - else if (ch == 2) - { - pop(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); - - return 0; -} diff --git a/data_structure/avltree.cpp b/data_structure/avltree.cpp new file mode 100644 index 000000000..f38133c05 --- /dev/null +++ b/data_structure/avltree.cpp @@ -0,0 +1,151 @@ +#include +#include + +using namespace std; + +typedef struct node { + int data; + int height; + struct node *left; + struct node *right; +} node; + +int max(int a, int b) { return a > b ? a : b; } + +// Returns a new Node + +node *createNode(int data) { + node *nn = new node(); + nn->data = data; + nn->height = 0; + nn->left = NULL; + nn->right = NULL; + return nn; +} + +// Returns height of tree + +int height(node *root) { + if (root == NULL) + return 0; + return 1 + max(height(root->left), height(root->right)); +} + +// Returns difference between height of left and right subtree + +int getBalance(node *root) { return height(root->left) - height(root->right); } + +// Returns Node after Right Rotation + +node *rightRotate(node *root) { + node *t = root->left; + node *u = t->right; + t->right = root; + root->left = u; + return t; +} + +// Returns Node after Left Rotation + +node *leftRotate(node *root) { + node *t = root->right; + node *u = t->left; + t->left = root; + root->right = u; + return t; +} + +// Returns node with minimum value in the tree + +node *minValue(node *root) { + if (root->left == NULL) + return root; + return minValue(root->left); +} + +// Balanced Insertion + +node *insert(node *root, int item) { + node *nn = createNode(item); + if (root == NULL) + return nn; + if (item < root->data) + root->left = insert(root->left, item); + else + root->right = insert(root->right, item); + int b = getBalance(root); + if (b > 1) { + if (getBalance(root->left) < 0) + root->left = leftRotate(root->left); // Left-Right Case + return rightRotate(root); // Left-Left Case + } else if (b < -1) { + if (getBalance(root->right) > 0) + root->right = rightRotate(root->right); // Right-Left Case + return leftRotate(root); // Right-Right Case + } + return root; +} + +// Balanced Deletion + +node *deleteNode(node *root, int key) { + if (root == NULL) + return root; + if (key < root->data) + root->left = deleteNode(root->left, key); + else if (key > root->data) + root->right = deleteNode(root->right, key); + + else { + // Node to be deleted is leaf node or have only one Child + if (!root->right) { + node *temp = root->left; + delete (root); + root = NULL; + return temp; + } else if (!root->left) { + node *temp = root->right; + delete (root); + root = NULL; + return temp; + } + // Node to be deleted have both left and right subtrees + node *temp = minValue(root->right); + root->data = temp->data; + root->right = deleteNode(root->right, temp->data); + } + // Balancing Tree after deletion + return root; +} + +// LevelOrder (Breadth First Search) + +void levelOrder(node *root) { + queue q; + q.push(root); + while (!q.empty()) { + root = q.front(); + cout << root->data << " "; + q.pop(); + if (root->left) + q.push(root->left); + if (root->right) + q.push(root->right); + } +} + +int main() { + // Testing AVL Tree + node *root = NULL; + int i; + for (i = 1; i <= 7; i++) root = insert(root, i); + cout << "LevelOrder: "; + levelOrder(root); + root = deleteNode(root, 1); // Deleting key with value 1 + cout << "\nLevelOrder: "; + levelOrder(root); + root = deleteNode(root, 4); // Deletin key with value 4 + cout << "\nLevelOrder: "; + levelOrder(root); + return 0; +} diff --git a/data_structure/binary_search_tree.cpp b/data_structure/binary_search_tree.cpp new file mode 100644 index 000000000..c3a74f385 --- /dev/null +++ b/data_structure/binary_search_tree.cpp @@ -0,0 +1,165 @@ +#include +using namespace std; + +struct node { + int val; + node *left; + node *right; +}; + +struct queue { + node *t[100]; + int front; + int rear; +}; + +queue q; + +void enqueue(node *n) { q.t[q.rear++] = n; } + +node *dequeue() { return (q.t[q.front++]); } + +void Insert(node *n, int x) { + if (x < n->val) { + if (n->left == NULL) { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } else { + Insert(n->left, x); + } + } else { + if (n->right == NULL) { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } else { + Insert(n->right, x); + } + } +} + +int findMaxInLeftST(node *n) { + while (n->right != NULL) { + n = n->right; + } + return n->val; +} + +void Remove(node *p, node *n, int x) { + if (n->val == x) { + if (n->right == NULL && n->left == NULL) { + if (x < p->val) { + p->right = NULL; + } else { + p->left = NULL; + } + } else if (n->right == NULL) { + if (x < p->val) { + p->right = n->left; + } else { + p->left = n->left; + } + } else if (n->left == NULL) { + if (x < p->val) { + p->right = n->right; + } else { + p->left = n->right; + } + } else { + int y = findMaxInLeftST(n->left); + n->val = y; + Remove(n, n->right, y); + } + } else if (x < n->val) { + Remove(n, n->left, x); + } else { + Remove(n, n->right, x); + } +} + +void BFT(node *n) { + if (n != NULL) { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } +} + +void Pre(node *n) { + if (n != NULL) { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } +} + +void In(node *n) { + if (n != NULL) { + In(n->left); + cout << n->val << " "; + In(n->right); + } +} + +void Post(node *n) { + if (n != NULL) { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } +} + +int main() { + q.front = 0; + q.rear = 0; + int value; + int ch; + node *root = new node; + cout << "\nEnter the value of root node :"; + cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; + do { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Breadth First"; + cout << "\n4. Preorder Depth First"; + cout << "\n5. Inorder Depth First"; + cout << "\n6. Postorder Depth First"; + + cout << "\nEnter Your Choice : "; + cin >> ch; + int x; + switch (ch) { + case 1: + cout << "\nEnter the value to be Inserted : "; + cin >> x; + Insert(root, x); + break; + case 2: + cout << "\nEnter the value to be Deleted : "; + cin >> x; + Remove(root, root, x); + break; + case 3: + BFT(root); + break; + case 4: + Pre(root); + break; + case 5: + In(root); + break; + case 6: + Post(root); + break; + } + } while (ch != 0); +} diff --git a/data_structure/Binaryheap.cpp b/data_structure/binaryheap.cpp similarity index 82% rename from data_structure/Binaryheap.cpp rename to data_structure/binaryheap.cpp index 31129a823..a31d87674 100644 --- a/data_structure/Binaryheap.cpp +++ b/data_structure/binaryheap.cpp @@ -1,18 +1,17 @@ // A C++ program to demonstrate common Binary Heap Operations -#include #include +#include using namespace std; // Prototype of a utility function to swap two integers void swap(int *x, int *y); // A class for Min Heap -class MinHeap -{ - int *harr; // pointer to array of elements in heap - int capacity; // maximum possible size of min heap - int heap_size; // Current number of elements in min heap -public: +class MinHeap { + int *harr; // pointer to array of elements in heap + int capacity; // maximum possible size of min heap + int heap_size; // Current number of elements in min heap + public: // Constructor MinHeap(int capacity); @@ -44,18 +43,15 @@ public: }; // Constructor: Builds a heap from a given array a[] of given size -MinHeap::MinHeap(int cap) -{ +MinHeap::MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } // Inserts a new key 'k' -void MinHeap::insertKey(int k) -{ - if (heap_size == capacity) - { +void MinHeap::insertKey(int k) { + if (heap_size == capacity) { cout << "\nOverflow: Could not insertKey\n"; return; } @@ -66,8 +62,7 @@ void MinHeap::insertKey(int k) harr[i] = k; // Fix the min heap property if it is violated - while (i != 0 && harr[parent(i)] > harr[i]) - { + while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); } @@ -75,23 +70,19 @@ void MinHeap::insertKey(int k) // Decreases value of key at index 'i' to new_val. It is assumed that // new_val is smaller than harr[i]. -void MinHeap::decreaseKey(int i, int new_val) -{ +void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; - while (i != 0 && harr[parent(i)] > harr[i]) - { + while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); } } // Method to remove minimum element (or root) from min heap -int MinHeap::extractMin() -{ +int MinHeap::extractMin() { if (heap_size <= 0) return INT_MAX; - if (heap_size == 1) - { + if (heap_size == 1) { heap_size--; return harr[0]; } @@ -107,16 +98,14 @@ int MinHeap::extractMin() // This function deletes key at index i. It first reduced value to minus // infinite, then calls extractMin() -void MinHeap::deleteKey(int i) -{ +void MinHeap::deleteKey(int i) { decreaseKey(i, INT_MIN); extractMin(); } // A recursive method to heapify a subtree with the root at given index // This method assumes that the subtrees are already heapified -void MinHeap::MinHeapify(int i) -{ +void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; @@ -124,24 +113,21 @@ void MinHeap::MinHeapify(int i) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; - if (smallest != i) - { + if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); } } // A utility function to swap two elements -void swap(int *x, int *y) -{ +void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // Driver program to test above functions -int main() -{ +int main() { MinHeap h(11); h.insertKey(3); h.insertKey(2); diff --git a/data_structure/circular_Queue_using_Linked_List.cpp b/data_structure/circular_queue_using_linked_list.cpp similarity index 78% rename from data_structure/circular_Queue_using_Linked_List.cpp rename to data_structure/circular_queue_using_linked_list.cpp index 4b1ec476c..b6a471044 100644 --- a/data_structure/circular_Queue_using_Linked_List.cpp +++ b/data_structure/circular_queue_using_linked_list.cpp @@ -1,24 +1,20 @@ #include using namespace std; -struct node -{ +struct node { int data; struct node *next; }; -class Queue -{ +class Queue { node *front; node *rear; -public: - Queue() - { + public: + Queue() { front = NULL; rear = NULL; } - void createNode(int val) - { + void createNode(int val) { node *ptr; node *nn; nn = new node; @@ -28,14 +24,10 @@ public: front = nn; rear = nn; } - void enqueue(int val) - { - if (front == NULL || rear == NULL) - { + void enqueue(int val) { + if (front == NULL || rear == NULL) { createNode(val); - } - else - { + } else { node *ptr; node *nn; ptr = front; @@ -46,19 +38,16 @@ public: rear = nn; } } - void dequeue() - { + void dequeue() { node *n; n = front; front = front->next; delete (n); } - void traverse() - { + void traverse() { node *ptr; ptr = front; - do - { + do { cout << ptr->data << " "; ptr = ptr->next; } while (ptr != rear->next); @@ -66,8 +55,7 @@ public: cout << endl; } }; -int main(void) -{ +int main(void) { Queue q; q.enqueue(10); q.enqueue(20); diff --git a/data_structure/cll/cll.cpp b/data_structure/cll/cll.cpp index efc068f3c..42bc9067e 100644 --- a/data_structure/cll/cll.cpp +++ b/data_structure/cll/cll.cpp @@ -5,49 +5,42 @@ using namespace std; /* Constructor */ -cll::cll() -{ +cll::cll() { head = NULL; total = 0; } -cll::~cll() -{ - /* Desstructure, no need to fill */ +cll::~cll() { /* Desstructure, no need to fill */ } /* Display a list. and total element */ -void cll::display() -{ +void cll::display() { if (head == NULL) cout << "List is empty !" << endl; - else - { + else { cout << "CLL list: "; node *current = head; - for (int i = 0; i < total; i++) - { + for (int i = 0; i < total; i++) { cout << current->data << " -> "; - current = current ->next; + current = current->next; } cout << head->data << endl; - cout << "Total element: "<< total <data = new_data; newNode->next = NULL; - if(head==NULL) { + if (head == NULL) { head = newNode; - head -> next = head; + head->next = head; } else { node *current = head; - while (current -> next != head) { + while (current->next != head) { current = current->next; } newNode->next = head; @@ -58,18 +51,17 @@ void cll::insert_front(int new_data) } /* List insert a new value at head in list */ -void cll::insert_tail(int new_data) -{ +void cll::insert_tail(int new_data) { node *newNode; newNode = new node; newNode->data = new_data; newNode->next = NULL; - if(head==NULL) { + if (head == NULL) { head = newNode; - head -> next = head; + head->next = head; } else { node *current = head; - while (current -> next != head) { + while (current->next != head) { current = current->next; } current->next = newNode; @@ -79,22 +71,17 @@ void cll::insert_tail(int new_data) } /* Get total element in list */ -int cll::get_size() -{ - return total; -} - +int cll::get_size() { return total; } /* Return true if the requested item (sent in as an argument) is in the list, otherwise return false */ -bool cll::find_item(int item_to_find) -{ +bool cll::find_item(int item_to_find) { if (head == NULL) { cout << "List is empty !" << endl; return false; } else { node *current = head; - while (current -> next != head) { + while (current->next != head) { if (current->data == item_to_find) return true; current = current->next; @@ -104,24 +91,20 @@ bool cll::find_item(int item_to_find) } /* Overloading method*/ -int cll::operator*() -{ - return head->data; -} +int cll::operator*() { return head->data; } /* Overload the pre-increment operator. The iterator is advanced to the next node. */ -void cll::operator++() -{ +void cll::operator++() { if (head == NULL) { cout << "List is empty !" << endl; } else { node *current = head; - while (current -> next != head) { - current = current -> next; + while (current->next != head) { + current = current->next; } - current->next = head -> next; - head = head -> next; + current->next = head->next; + head = head->next; } total--; } diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h index ae71dcd01..a1a9b4d92 100644 --- a/data_structure/cll/cll.h +++ b/data_structure/cll/cll.h @@ -1,45 +1,43 @@ /* * Simple data structure CLL (Cicular Linear Linked List) * */ -#include #include -#include #include +#include +#include #ifndef CLL_H #define CLL_H /*The data structure is a linear linked list of integers */ -struct node -{ - int data; - node * next; +struct node { + int data; + node* next; }; -class cll -{ - public: - cll(); /* Construct without parameter */ - ~cll(); - void display(); /* Show the list */ +class cll { + public: + cll(); /* Construct without parameter */ + ~cll(); + void display(); /* Show the list */ - /****************************************************** - * Useful method for list - *******************************************************/ - void insert_front(int new_data); /* Insert a new value at head */ - void insert_tail(int new_data); /* Insert a new value at tail */ - int get_size(); /* Get total element in list */ - bool find_item(int item_to_find); /* Find an item in list */ + /****************************************************** + * Useful method for list + *******************************************************/ + void insert_front(int new_data); /* Insert a new value at head */ + void insert_tail(int new_data); /* Insert a new value at tail */ + int get_size(); /* Get total element in list */ + bool find_item(int item_to_find); /* Find an item in list */ - /****************************************************** - * Overloading method for list - *******************************************************/ - int operator*(); /* Returns the info contained in head */ - /* Overload the pre-increment operator. - The iterator is advanced to the next node. */ - void operator++(); + /****************************************************** + * Overloading method for list + *******************************************************/ + int operator*(); /* Returns the info contained in head */ + /* Overload the pre-increment operator. + The iterator is advanced to the next node. */ + void operator++(); - protected: - node * head; - int total; /* Total element in a list */ + protected: + node* head; + int total; /* Total element in a list */ }; #endif diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp index 15388b822..0b6bfd3ed 100644 --- a/data_structure/cll/main_cll.cpp +++ b/data_structure/cll/main_cll.cpp @@ -1,44 +1,43 @@ #include "cll.h" using namespace std; -int main() -{ - /* Test CLL */ - cout << "----------- Test construct -----------" << endl; - cll list1; - list1.display(); - cout << "----------- Test insert front -----------" << endl; - list1.insert_front(5); - cout << "After insert 5 at front: "< root, rnk; void CreateSet(int n) { - root = vector (n+1); - rnk = vector (n+1, 1); - for (int i = 1; i <= n; ++i) { - root[i] = i; - } + root = vector(n + 1); + rnk = vector(n + 1, 1); + for (int i = 1; i <= n; ++i) { + root[i] = i; + } } int Find(int x) { - if (root[x] == x) { - return x; - } - return root[x] = Find(root[x]); + if (root[x] == x) { + return x; + } + return root[x] = Find(root[x]); } -bool InSameUnion(int x, int y) { - return Find(x) == Find(y); -} +bool InSameUnion(int x, int y) { return Find(x) == Find(y); } void Union(int x, int y) { - int a = Find(x), b = Find(y); - if (a != b) { - if (rnk[a] < rnk[b]) { - root[a] = b; - } else if (rnk[a] > rnk[b]) { - root[b] = a; - } else { - root[a] = b; - ++rnk[b]; + int a = Find(x), b = Find(y); + if (a != b) { + if (rnk[a] < rnk[b]) { + root[a] = b; + } else if (rnk[a] > rnk[b]) { + root[b] = a; + } else { + root[a] = b; + ++rnk[b]; + } } - } } int main() { - // tests CreateSet & Find - int n = 100; - CreateSet(n); - for (int i = 1; i <= 100; ++i) { - if (root[i] != i) { - cout << "Fail" << endl; - break; + // tests CreateSet & Find + int n = 100; + CreateSet(n); + for (int i = 1; i <= 100; ++i) { + if (root[i] != i) { + cout << "Fail" << endl; + break; + } } - } - // tests InSameUnion & Union - cout << "1 and 2 are initially not in the same subset" << endl; - if (InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - Union(1, 2); - cout << "1 and 2 are now in the same subset" << endl; - if (!InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - return 0; + // tests InSameUnion & Union + cout << "1 and 2 are initially not in the same subset" << endl; + if (InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + Union(1, 2); + cout << "1 and 2 are now in the same subset" << endl; + if (!InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + return 0; } diff --git a/data_structure/doubly_linked_list.cpp b/data_structure/doubly_linked_list.cpp index 4fc38abfc..30cc257d8 100644 --- a/data_structure/doubly_linked_list.cpp +++ b/data_structure/doubly_linked_list.cpp @@ -1,138 +1,136 @@ +#include +#include #include -#include -#include struct node { - int val; - node *prev; - node *next; -}*start; + int val; + node *prev; + node *next; +} * start; class double_linked_list { public: - double_linked_list() { - start = NULL; - } - void insert(int x); - void remove(int x); - void search(int x); - void show(); - void reverseShow(); + double_linked_list() { start = NULL; } + void insert(int x); + void remove(int x); + void search(int x); + void show(); + void reverseShow(); }; void double_linked_list::insert(int x) { - node *t = start; - if (start != NULL) { - while (t->next != NULL) { - t = t->next; + node *t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + node *n = new node; + t->next = n; + n->prev = t; + n->val = x; + n->next = NULL; + } else { + node *n = new node; + n->val = x; + n->prev = NULL; + n->next = NULL; + start = n; } - node *n = new node; - t->next = n; - n->prev = t; - n->val = x; - n->next = NULL; - } else { - node *n = new node; - n->val = x; - n->prev = NULL; - n->next = NULL; - start = n; - } } void double_linked_list::remove(int x) { - node *t = start; - while (t != NULL && t->val != x) { - t = t-> next; - } - if (t == NULL) { - return; - } - if (t->prev == NULL) { - if (t->next == NULL) { - start = NULL; - } else { - start = t->next; - start->prev = NULL; + node *t = start; + while (t != NULL && t->val != x) { + t = t->next; } - } else if (t->next == NULL) { - t->prev->next = NULL; - } else { - t->prev->next = t->next; - t->next->prev = t->prev; - } - delete t; + if (t == NULL) { + return; + } + if (t->prev == NULL) { + if (t->next == NULL) { + start = NULL; + } else { + start = t->next; + start->prev = NULL; + } + } else if (t->next == NULL) { + t->prev->next = NULL; + } else { + t->prev->next = t->next; + t->next->prev = t->prev; + } + delete t; } void double_linked_list::search(int x) { - node *t = start; - int found = 0; - while (t != NULL) { - if (t->val == x) { - std::cout << "\nFound"; - found = 1; - break; + node *t = start; + int found = 0; + while (t != NULL) { + if (t->val == x) { + std::cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + std::cout << "\nNot Found"; } - t = t->next; - } - if (found == 0) { - std::cout << "\nNot Found"; - } } void double_linked_list::show() { - node *t = start; - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->next; - } + node *t = start; + while (t != NULL) { + std::cout << t->val << "\t"; + t = t->next; + } } void double_linked_list::reverseShow() { - node *t = start; - while (t != NULL && t->next != NULL) { - t = t->next; - } - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->prev; - } + node *t = start; + while (t != NULL && t->next != NULL) { + t = t->next; + } + while (t != NULL) { + std::cout << t->val << "\t"; + t = t->prev; + } } int main() { - int choice, x; - double_linked_list ob; - do { - std::cout << "\n1. Insert"; - std::cout << "\n2. Delete"; - std::cout << "\n3. Search"; - std::cout << "\n4. Forward print"; - std::cout << "\n5. Reverse print"; - std::cout << "\n\nEnter you choice : "; - std::cin >> choice; - switch (choice) { - case 1: - std::cout << "\nEnter the element to be inserted : "; - std::cin >> x; - ob.insert(x); - break; - case 2: - std::cout << "\nEnter the element to be removed : "; - std::cin >> x; - ob.remove(x); - break; - case 3: - std::cout << "\nEnter the element to be searched : "; - std::cin >> x; - ob.search(x); - break; - case 4: - ob.show(); - break; - case 5: - ob.reverseShow(); - break; - } - } while (choice != 0); - return 0; + int choice, x; + double_linked_list ob; + do { + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Forward print"; + std::cout << "\n5. Reverse print"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; + switch (choice) { + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + ob.insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + ob.remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + ob.search(x); + break; + case 4: + ob.show(); + break; + case 5: + ob.reverseShow(); + break; + } + } while (choice != 0); + return 0; } diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp index 64cad14f9..8eb6e586d 100644 --- a/data_structure/linked_list.cpp +++ b/data_structure/linked_list.cpp @@ -1,135 +1,134 @@ #include struct node { - int val; - node *next; + int val; + node *next; }; node *start; void insert(int x) { - node *t = start; - node *n = new node; - n->val = x; - n->next = NULL; - if (start != NULL) { - while (t->next != NULL) { - t = t->next; - } - t->next = n; - } else { - start = n; + node *t = start; + node *n = new node; + n->val = x; + n->next = NULL; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; } - + t->next = n; + } else { + start = n; + } } void remove(int x) { - if (start == NULL) { - std::cout << "\nLinked List is empty\n"; - return; - } else if (start->val == x) { - node *temp = start; - start = start->next; - delete temp; - return; - } - - node *temp = start, *parent = start; - - while (temp != NULL && temp->val != x) { - parent = temp; - temp = temp->next; - } - - if (temp == NULL) { - std::cout << std::endl << x << " not found in list\n"; - return; - } - - parent->next = temp->next; + if (start == NULL) { + std::cout << "\nLinked List is empty\n"; + return; + } else if (start->val == x) { + node *temp = start; + start = start->next; delete temp; + return; + } + + node *temp = start, *parent = start; + + while (temp != NULL && temp->val != x) { + parent = temp; + temp = temp->next; + } + + if (temp == NULL) { + std::cout << std::endl << x << " not found in list\n"; + return; + } + + parent->next = temp->next; + delete temp; } void search(int x) { - node *t = start; - int found = 0; - while (t != NULL) { - if (t->val == x) { - std::cout << "\nFound"; - found = 1; - break; - } - t = t->next; - } - if (found == 0) { - std::cout << "\nNot Found"; + node *t = start; + int found = 0; + while (t != NULL) { + if (t->val == x) { + std::cout << "\nFound"; + found = 1; + break; } + t = t->next; + } + if (found == 0) { + std::cout << "\nNot Found"; + } } void show() { - node *t = start; - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->next; - } + node *t = start; + while (t != NULL) { + std::cout << t->val << "\t"; + t = t->next; + } } void reverse() { - node *first = start; - if (first != NULL) { - node *second = first->next; - while (second != NULL) { - node *tem = second->next; - second->next = first; - first = second; - second = tem; - } - start->next = NULL; - start = first; - } else { - std::cout << "\nEmpty list"; + node *first = start; + if (first != NULL) { + node *second = first->next; + while (second != NULL) { + node *tem = second->next; + second->next = first; + first = second; + second = tem; } + start->next = NULL; + start = first; + } else { + std::cout << "\nEmpty list"; + } } int main() { - int choice, x; - do { - std::cout << "\n1. Insert"; - std::cout << "\n2. Delete"; - std::cout << "\n3. Search"; - std::cout << "\n4. Print"; - std::cout << "\n5. Reverse"; - std::cout << "\n0. Exit"; - std::cout << "\n\nEnter you choice : "; - std::cin >> choice; - switch (choice) { - case 1: - std::cout << "\nEnter the element to be inserted : "; - std::cin >> x; - insert(x); - break; - case 2: - std::cout << "\nEnter the element to be removed : "; - std::cin >> x; - remove(x); - break; - case 3: - std::cout << "\nEnter the element to be searched : "; - std::cin >> x; - search(x); - break; - case 4: - show(); - std::cout << "\n"; - break; - case 5: - std::cout << "The reversed list: \n"; - reverse(); - show(); - std::cout << "\n"; - break; - } - } while (choice != 0); + int choice, x; + do { + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Print"; + std::cout << "\n5. Reverse"; + std::cout << "\n0. Exit"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; + switch (choice) { + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + search(x); + break; + case 4: + show(); + std::cout << "\n"; + break; + case 5: + std::cout << "The reversed list: \n"; + reverse(); + show(); + std::cout << "\n"; + break; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/data_structure/linkedList_implentation_usingArray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp similarity index 62% rename from data_structure/linkedList_implentation_usingArray.cpp rename to data_structure/linkedlist_implentation_usingarray.cpp index 6f8205f27..a078bef16 100644 --- a/data_structure/linkedList_implentation_usingArray.cpp +++ b/data_structure/linkedlist_implentation_usingarray.cpp @@ -1,41 +1,45 @@ -/* The difference between the pointer implementation of linked list and array implementation of linked list: +/* The difference between the pointer implementation of linked list and array + implementation of linked list: 1. The NULL is represented by -1; - 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. + 2. Limited size. (in the following case it is 100 nodes at max). But we can + reuse the nodes that are to be deleted by again linking it bacj to the list. */ #include using namespace std; -struct Node -{ +struct Node { int data; int next; }; -Node AvailArray[100]; //array that will act as nodes of a linked list. +Node AvailArray[100]; // array that will act as nodes of a linked list. int head = -1; int avail = 0; -void initialise_list() -{ - for (int i = 0; i <= 98; i++) - { +void initialise_list() { + for (int i = 0; i <= 98; i++) { AvailArray[i].next = i + 1; } - AvailArray[99].next = -1; //indicating the end of the linked list. + AvailArray[99].next = -1; // indicating the end of the linked list. } -int getnode() //This will return the index of the first free node present in the avail list +int getnode() // This will return the index of the first free node present in + // the avail list { int NodeIndexToBeReturned = avail; avail = AvailArray[avail].next; return NodeIndexToBeReturned; } -void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. +void freeNode( + int nodeToBeDeleted) // This function when called will delete the node with + // the index presented as an argument, and will put + // back that node into the array. { AvailArray[nodeToBeDeleted].next = avail; avail = nodeToBeDeleted; } -void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. +void insertAtTheBeginning(int data) // The function will insert the given data + // into the front of the linked list. { int newNode = getnode(); AvailArray[newNode].data = data; @@ -43,25 +47,21 @@ void insertAtTheBeginning(int data) //The function will insert the given data in head = newNode; } -void insertAtTheEnd(int data) -{ +void insertAtTheEnd(int data) { int newNode = getnode(); int temp = head; - while (AvailArray[temp].next != -1) - { + while (AvailArray[temp].next != -1) { temp = AvailArray[temp].next; } - //temp is now pointing to the end node. + // temp is now pointing to the end node. AvailArray[newNode].data = data; AvailArray[newNode].next = -1; AvailArray[temp].next = newNode; } -void display() -{ +void display() { int temp = head; - while (temp != -1) - { + while (temp != -1) { cout << AvailArray[temp].data << "->"; temp = AvailArray[temp].next; } @@ -69,20 +69,17 @@ void display() ; } -int main() -{ +int main() { initialise_list(); int x, y, z; - for (;;) - { + for (;;) { cout << "1. Insert At The Beginning" << endl; cout << "2. Insert At The End" << endl; cout << "3. Display" << endl; cout << "4.Exit" << endl; cout << "Enter Your choice" << endl; cin >> z; - switch (z) - { + switch (z) { case 1: cout << "Enter the number you want to enter" << endl; cin >> x; @@ -94,7 +91,8 @@ int main() insertAtTheEnd(y); break; case 3: - cout << "The linked list contains the following element in order" << endl; + cout << "The linked list contains the following element in order" + << endl; display(); break; case 4: diff --git a/data_structure/list_array.cpp b/data_structure/list_array.cpp new file mode 100644 index 000000000..c796ffef9 --- /dev/null +++ b/data_structure/list_array.cpp @@ -0,0 +1,153 @@ +#include +using namespace std; + +struct list { + int data[50]; + int top = 0; + bool isSorted = false; + + int BinarySearch(int *array, int first, int last, int x) { + if (last < first) { + return -1; + } + int mid = (first + last) / 2; + if (array[mid] == x) + return mid; + else if (x < array[mid]) + return (BinarySearch(array, first, mid - 1, x)); + else if (x > array[mid]) + return (BinarySearch(array, mid + 1, last, x)); + } + + int LinarSearch(int *array, int x) { + for (int i = 0; i < top; i++) { + if (array[i] == x) { + return i; + } + } + + return -1; + } + + int Search(int x) { + int pos = -1; + + if (isSorted) { + pos = BinarySearch(data, 0, top - 1, x); + } + + else { + pos = LinarSearch(data, x); + } + + if (pos != -1) { + cout << "\nElement found at position : " << pos; + } else { + cout << "\nElement not found"; + } + return pos; + } + + void Sort() { + int i, j, pos; + for (i = 0; i < top; i++) { + int min = data[i]; + for (j = i + 1; j < top; j++) { + if (data[j] < min) { + pos = j; + min = data[pos]; + } + } + + int temp = data[i]; + data[i] = data[pos]; + data[pos] = temp; + } + isSorted = true; + } + + void insert(int x) { + if (!isSorted) { + if (top == 49) { + cout << "\nOverflow"; + } else { + data[top] = x; + top++; + } + } + + else { + int pos = 0; + + for (int i = 0; i < top - 1; i++) { + if (data[i] <= x && x <= data[i + 1]) { + pos = i + 1; + break; + } + } + if (pos == 0) { + pos = top - 1; + } + + for (int i = top; i > pos; i--) { + data[i] = data[i - 1]; + } + top++; + data[pos] = x; + } + } + + void Remove(int x) { + int pos = Search(x); + cout << "\n" << data[pos] << " deleted"; + for (int i = pos; i < top; i++) { + data[i] = data[i + 1]; + } + top--; + } + + void Show() { + for (int i = 0; i < top; i++) { + cout << data[i] << "\t"; + } + } +}; + +int main() { + list L; + int choice; + int x; + do { + cout << "\n1.Insert"; + cout << "\n2.Delete"; + cout << "\n3.Search"; + cout << "\n4.Sort"; + cout << "\n5.Print"; + cout << "\n\nEnter Your Choice : "; + cin >> choice; + switch (choice) { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + L.insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + L.Remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + L.Search(x); + break; + case 4: + L.Sort(); + break; + case 5: + L.Show(); + break; + } + } while (choice != 0); + return 0; +} diff --git a/data_structure/morrisinorder.cpp b/data_structure/morrisinorder.cpp new file mode 100644 index 000000000..f1f9e068c --- /dev/null +++ b/data_structure/morrisinorder.cpp @@ -0,0 +1,92 @@ +#include +#include + +/************************** + @author shrutisheoran +**************************/ + +using namespace std; + +struct Btree { + int data; + struct Btree *left; // Pointer to left subtree + struct Btree *right; // Pointer to right subtree +}; + +void insert(Btree **root, int d) { + Btree *nn = new Btree(); // Creating new node + nn->data = d; + nn->left = NULL; + nn->right = NULL; + if (*root == NULL) { + *root = nn; + return; + } else { + queue q; + // Adding root node to queue + q.push(*root); + while (!q.empty()) { + Btree *node = q.front(); + // Removing parent node from queue + q.pop(); + if (node->left) + // Adding left child of removed node to queue + q.push(node->left); + else { + // Adding new node if no left child is present + node->left = nn; + return; + } + if (node->right) + // Adding right child of removed node to queue + q.push(node->right); + else { + // Adding new node if no right child is present + node->right = nn; + return; + } + } + } +} + +void morrisInorder(Btree *root) { + Btree *curr = root; + Btree *temp; + while (curr) { + if (curr->left == NULL) { + cout << curr->data << " "; + // If left of current node is NULL then curr is shifted to right + curr = curr->right; + } else { + // Left of current node is stored in temp + temp = curr->left; + // Moving to extreme right of temp + while (temp->right && temp->right != curr) temp = temp->right; + // If extreme right is null it is made to point to currrent node + // (will be used for backtracking) + if (temp->right == NULL) { + temp->right = curr; + // current node is made to point its left subtree + curr = curr->left; + } + // If extreme right already points to currrent node it it set to + // null + else if (temp->right == curr) { + cout << curr->data << " "; + temp->right = NULL; + // current node is made to point its right subtree + curr = curr->right; + } + } + } +} + +int main() { + // Testing morrisInorder funtion + Btree *root = NULL; + int i; + for (i = 1; i <= 7; i++) insert(&root, i); + cout << "Morris Inorder: "; + morrisInorder(root); + return 0; +} diff --git a/data_structure/queue/queue.cpp b/data_structure/queue/queue.cpp index 728adfc18..a7055bb14 100644 --- a/data_structure/queue/queue.cpp +++ b/data_structure/queue/queue.cpp @@ -1,13 +1,12 @@ -#include -#include #include "queue.h" +#include +#include using namespace std; /* Default constructor*/ template -queue::queue() -{ +queue::queue() { queueFront = NULL; queueRear = NULL; size = 0; @@ -15,42 +14,36 @@ queue::queue() /* Destructor */ template -queue::~queue() -{ -} +queue::~queue() {} /* Display for testing */ template -void queue::display() -{ +void queue::display() { node *current = queueFront; cout << "Front --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; + while (current != NULL) { + cout << current->data << " "; + current = current->next; } - cout < -bool queue::isEmptyQueue() -{ +bool queue::isEmptyQueue() { return (queueFront == NULL); } /* Clear queue */ template -void queue::clear() -{ +void queue::clear() { queueFront = NULL; } /* Add new item to the queue */ template -void queue::enQueue(Kind item) -{ +void queue::enQueue(Kind item) { node *newNode; newNode = new node; newNode->data = item; @@ -67,18 +60,16 @@ void queue::enQueue(Kind item) /* Return the top element of the queue */ template -Kind queue::front() -{ +Kind queue::front() { assert(queueFront != NULL); return queueFront->data; } /* Remove the element of the queue */ template -void queue::deQueue() -{ +void queue::deQueue() { node *temp; - if(!isEmptyQueue()) { + if (!isEmptyQueue()) { temp = queueFront; queueFront = queueFront->next; delete temp; @@ -87,4 +78,3 @@ void queue::deQueue() cout << "Queue is empty !" << endl; } } - diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h index 715def1ef..d1305fc81 100644 --- a/data_structure/queue/queue.h +++ b/data_structure/queue/queue.h @@ -4,31 +4,28 @@ /* Definition of the node */ template -struct node -{ +struct node { Kind data; node *next; }; /* Definition of the queue class */ template -class queue -{ - public: - void display(); /* Show queue */ - queue(); /* Default constructor*/ - ~queue(); /* Destructor */ - bool isEmptyQueue(); /* Determine whether the queue is empty */ - void enQueue (Kind item); /* Add new item to the queue */ - Kind front(); /* Return the first element of the queue */ - void deQueue(); /* Remove the top element of the queue */ - void clear(); +class queue { + public: + void display(); /* Show queue */ + queue(); /* Default constructor*/ + ~queue(); /* Destructor */ + bool isEmptyQueue(); /* Determine whether the queue is empty */ + void enQueue(Kind item); /* Add new item to the queue */ + Kind front(); /* Return the first element of the queue */ + void deQueue(); /* Remove the top element of the queue */ + void clear(); - private: - node *queueFront; /* Pointer to the front of the queue */ - node *queueRear; /* Pointer to the rear of the queue */ - int size; + private: + node *queueFront; /* Pointer to the front of the queue */ + node *queueRear; /* Pointer to the rear of the queue */ + int size; }; #endif - diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp index caf80318c..7f0923f78 100644 --- a/data_structure/queue/test_queue.cpp +++ b/data_structure/queue/test_queue.cpp @@ -1,22 +1,24 @@ #include #include -#include "queue.h" #include "queue.cpp" +#include "queue.h" using namespace std; -int main() -{ +int main() { queue q; - cout << "---------------------- Test construct ----------------------" << endl; + cout << "---------------------- Test construct ----------------------" + << endl; q.display(); - cout << "---------------------- Test isEmptyQueue ----------------------" << endl; - if(q.isEmptyQueue()) - cout << "PASS" < +using namespace std; + +int queue[10]; +int front = 0; +int rear = 0; + +void Enque(int x) { + if (rear == 10) { + cout << "\nOverflow"; + } else { + queue[rear++] = x; + } +} + +void Deque() { + if (front == rear) { + cout << "\nUnderflow"; + } + + else { + cout << "\n" << queue[front++] << " deleted"; + for (int i = front; i < rear; i++) { + queue[i - front] = queue[i]; + } + rear = rear - front; + front = 0; + } +} + +void show() { + for (int i = front; i < rear; i++) { + cout << queue[i] << "\t"; + } +} + +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/Queue Using Linked List.cpp b/data_structure/queue_using_linked_list.cpp similarity index 69% rename from data_structure/Queue Using Linked List.cpp rename to data_structure/queue_using_linked_list.cpp index 39d7a9ae3..7b44d240c 100644 --- a/data_structure/Queue Using Linked List.cpp +++ b/data_structure/queue_using_linked_list.cpp @@ -1,18 +1,15 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *front, *rear; -void Enque(int x) -{ - if (rear == NULL) - { +void Enque(int x) { + if (rear == NULL) { node *n = new node; n->val = x; n->next = NULL; @@ -20,9 +17,7 @@ void Enque(int x) front = n; } - else - { - + else { node *n = new node; n->val = x; n->next = NULL; @@ -31,17 +26,12 @@ void Enque(int x) } } -void Deque() -{ - if (rear == NULL && front == NULL) - { +void Deque() { + if (rear == NULL && front == NULL) { cout << "\nUnderflow"; - } - else - { + } else { node *t = front; - cout << "\n" - << t->val << " deleted"; + cout << "\n" << t->val << " deleted"; front = front->next; delete t; if (front == NULL) @@ -49,38 +39,29 @@ void Deque() } } -void show() -{ +void show() { node *t = front; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\t"; t = t->next; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Enque"; cout << "\n2. Deque"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; Enque(x); - } - else if (ch == 2) - { + } else if (ch == 2) { Deque(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp index 8bc130c27..f1bf18123 100644 --- a/data_structure/queue_using_linkedlist.cpp +++ b/data_structure/queue_using_linkedlist.cpp @@ -1,98 +1,86 @@ /* Write a program to implement Queue using linkedlist. */ -#include - - -struct linkedlist{ - int data; - linkedlist *next; +#include +struct linkedlist { + int data; + linkedlist *next; }; -class stack_linkedList{ - public: +class stack_linkedList { + public: linkedlist *front; linkedlist *rear; - - stack_linkedList(){ - front=rear=NULL; - } + + stack_linkedList() { front = rear = NULL; } void enqueue(int); int dequeue(); void display(); - }; -void stack_linkedList::enqueue(int ele){ - - linkedlist *temp=new linkedlist(); - temp->data=ele; - temp->next=NULL; +void stack_linkedList::enqueue(int ele) { + linkedlist *temp = new linkedlist(); + temp->data = ele; + temp->next = NULL; - if(front==NULL) - front=rear=temp; - else{ - rear->next=temp; - rear=temp; + if (front == NULL) + front = rear = temp; + else { + rear->next = temp; + rear = temp; } } -int stack_linkedList::dequeue(){ +int stack_linkedList::dequeue() { linkedlist *temp; int ele; - if(front==NULL) - std::cout<<"\nStack is empty"; - else{ - temp=front; - ele=temp->data; - if(front==rear) //if length of queue is 1; - rear=rear->next; - front=front->next; - delete(temp); + if (front == NULL) + std::cout << "\nStack is empty"; + else { + temp = front; + ele = temp->data; + if (front == rear) // if length of queue is 1; + rear = rear->next; + front = front->next; + delete (temp); } return ele; } -void stack_linkedList::display(){ - - if(front==NULL) - std::cout<<"\nStack is empty"; - +void stack_linkedList::display() { + if (front == NULL) + std::cout << "\nStack is empty"; + else { - linkedlist *temp; - temp=front; - while(temp!=NULL){ - std::cout<data<<" "; - temp=temp->next; + temp = front; + while (temp != NULL) { + std::cout << temp->data << " "; + temp = temp->next; } } } -int main(){ - - int op,data; +int main() { + int op, data; stack_linkedList ob; - std::cout<<"\n1. enqueue(Insertion) "; - std::cout<<"\n2. dequeue(Deletion)"; - std::cout<<"\n3. Display"; - std::cout<<"\n4. Exit"; - - while(1){ - std::cout<<"\nEnter your choice "; - std::cin>>op; - if(op==1) - { - std::cout<<"Enter data "; - std::cin>>data; + std::cout << "\n1. enqueue(Insertion) "; + std::cout << "\n2. dequeue(Deletion)"; + std::cout << "\n3. Display"; + std::cout << "\n4. Exit"; + + while (1) { + std::cout << "\nEnter your choice "; + std::cin >> op; + if (op == 1) { + std::cout << "Enter data "; + std::cin >> data; ob.enqueue(data); - } - else if(op==2) - data=ob.dequeue(); - else if(op==3) + } else if (op == 2) + data = ob.dequeue(); + else if (op == 3) ob.display(); - else if(op==4) + else if (op == 4) exit(0); else - std::cout<<"\nWrong choice "; - + std::cout << "\nWrong choice "; } return 0; } diff --git a/data_structure/stack_using_array.cpp b/data_structure/stack_using_array.cpp new file mode 100644 index 000000000..5dd7ac98e --- /dev/null +++ b/data_structure/stack_using_array.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +int *stack; +int top = 0, size; + +void push(int x) { + if (top == size) { + cout << "\nOverflow"; + } else { + stack[top++] = x; + } +} + +void pop() { + if (top == 0) { + cout << "\nUnderflow"; + } else { + cout << "\n" << stack[--top] << " deleted"; + } +} + +void show() { + for (int i = 0; i < top; i++) { + cout << stack[i] << "\n"; + } +} + +void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } +int main() { + cout << "\nEnter Size of stack : "; + cin >> size; + stack = new int[size]; + int ch, x; + do { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\n4. Print topmost element:"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } else if (ch == 4) { + topmost(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/stack_using_linked_list.cpp b/data_structure/stack_using_linked_list.cpp new file mode 100644 index 000000000..ae53fe95a --- /dev/null +++ b/data_structure/stack_using_linked_list.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +struct node { + int val; + node *next; +}; + +node *top; + +void push(int x) { + node *n = new node; + n->val = x; + n->next = top; + top = n; +} + +void pop() { + if (top == NULL) { + cout << "\nUnderflow"; + } else { + node *t = top; + cout << "\n" << t->val << " deleted"; + top = top->next; + delete t; + } +} + +void show() { + node *t = top; + while (t != NULL) { + cout << t->val << "\n"; + t = t->next; + } +} + +int main() { + int ch, x; + do { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/stk/main.cpp b/data_structure/stk/main.cpp index 2d6bbec56..44b7984e0 100644 --- a/data_structure/stk/main.cpp +++ b/data_structure/stk/main.cpp @@ -8,18 +8,18 @@ * ./main student.txt ************************************************************ * */ -#include -#include -#include -#include #include +#include +#include +#include +#include -#include "stack.h" #include "stack.cpp" +#include "stack.h" using namespace std; -int main(int argc, char * argv[]) { +int main(int argc, char* argv[]) { double GPA; double highestGPA; string name; @@ -44,7 +44,7 @@ int main(int argc, char * argv[]) { } infile >> GPA >> name; } - cout << "Highest GPA: " << highestGPA < -#include #include "stack.h" +#include +#include using namespace std; /* Default constructor*/ template -stack::stack() -{ +stack::stack() { stackTop = NULL; size = 0; } /* Destructor */ template -stack::~stack() -{ -} +stack::~stack() {} /* Display for testing */ template -void stack::display() -{ +void stack::display() { node *current = stackTop; cout << "Top --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; + while (current != NULL) { + cout << current->data << " "; + current = current->next; } - cout < -bool stack::isEmptyStack() -{ +bool stack::isEmptyStack() { return (stackTop == NULL); } /* Clear stack */ template -void stack::clear() -{ +void stack::clear() { stackTop = NULL; } /* Add new item to the stack */ template -void stack::push(Type item) -{ +void stack::push(Type item) { node *newNode; newNode = new node; newNode->data = item; @@ -60,18 +53,16 @@ void stack::push(Type item) /* Return the top element of the stack */ template -Type stack::top() -{ +Type stack::top() { assert(stackTop != NULL); return stackTop->data; } /* Remove the top element of the stack */ template -void stack::pop() -{ +void stack::pop() { node *temp; - if(!isEmptyStack()) { + if (!isEmptyStack()) { temp = stackTop; stackTop = stackTop->next; delete temp; @@ -83,8 +74,7 @@ void stack::pop() /* Operator "=" */ template -stack stack::operator=(stack & otherStack) -{ +stack stack::operator=(stack &otherStack) { node *newNode, *current, *last; if (stackTop != NULL) /* If stack is no empty, make it empty */ @@ -97,10 +87,9 @@ stack stack::operator=(stack & otherStack) stackTop->data = current->data; stackTop->next = NULL; last = stackTop; - current = current ->next; + current = current->next; /* Copy the remaining stack */ - while (current != NULL) - { + while (current != NULL) { newNode = new node; newNode->data = current->data; newNode->next = NULL; diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h index a93669482..da7788b73 100644 --- a/data_structure/stk/stack.h +++ b/data_structure/stk/stack.h @@ -4,32 +4,29 @@ /* Definition of the node */ template -struct node -{ +struct node { Type data; node *next; }; /* Definition of the stack class */ template -class stack -{ - public: - void display(); /* Show stack */ - stack(); /* Default constructor*/ - ~stack(); /* Destructor */ - bool isEmptyStack(); /* Determine whether the stack is empty */ - void push (Type item); /* Add new item to the stack */ - Type top(); /* Return the top element of the stack */ - void pop(); /* Remove the top element of the stack */ - void clear(); +class stack { + public: + void display(); /* Show stack */ + stack(); /* Default constructor*/ + ~stack(); /* Destructor */ + bool isEmptyStack(); /* Determine whether the stack is empty */ + void push(Type item); /* Add new item to the stack */ + Type top(); /* Return the top element of the stack */ + void pop(); /* Remove the top element of the stack */ + void clear(); - stack operator=(stack & otherStack); - // Overload "=" the assignment operator. - private: - node *stackTop; /* Pointer to the stack */ - int size; + stack operator=(stack &otherStack); + // Overload "=" the assignment operator. + private: + node *stackTop; /* Pointer to the stack */ + int size; }; #endif - diff --git a/data_structure/stk/test_stack.cpp b/data_structure/stk/test_stack.cpp index 4703fc906..098027dfd 100644 --- a/data_structure/stk/test_stack.cpp +++ b/data_structure/stk/test_stack.cpp @@ -1,21 +1,22 @@ #include -#include "stack.h" #include "stack.cpp" +#include "stack.h" using namespace std; -int main() -{ +int main() { stack stk; - cout << "---------------------- Test construct ----------------------" << endl; + cout << "---------------------- Test construct ----------------------" + << endl; stk.display(); - cout << "---------------------- Test isEmptyStack ----------------------" << endl; - if(stk.isEmptyStack()) - cout << "PASS" < stk1; - cout << "stk current: "<< endl; + cout << "stk current: " << endl; stk.display(); - cout << endl << "Assign stk1 = stk "<< endl; + cout << endl << "Assign stk1 = stk " << endl; stk1 = stk; stk1.display(); - cout << endl<< "After pushing 8 9 10 into stk1:" < using namespace std; -struct node -{ +struct node { int val; node *left; node *right; }; -void CreateTree(node *curr, node *n, int x, char pos) -{ - if (n != NULL) - { +void CreateTree(node *curr, node *n, int x, char pos) { + if (n != NULL) { char ch; - cout << "\nLeft or Right of " << n->val << " : "; - cin >> ch; - if (ch == 'l') - CreateTree(n, n->left, x, ch); - else if (ch == 'r') - CreateTree(n, n->right, x, ch); - } - else - { + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') + CreateTree(n, n->left, x, ch); + else if (ch == 'r') + CreateTree(n, n->right, x, ch); + } else { node *t = new node; t->val = x; t->left = NULL; t->right = NULL; - if (pos == 'l') - { + if (pos == 'l') { curr->left = t; - } - else if (pos == 'r') - { + } else if (pos == 'r') { curr->right = t; } } } -void BFT(node *n) -{ - list queue; +void BFT(node *n) { + list queue; queue.push_back(n); - while(!queue.empty()) - { + while (!queue.empty()) { n = queue.front(); cout << n->val << " "; queue.pop_front(); - if(n->left != NULL) + if (n->left != NULL) queue.push_back(n->left); - if(n->right != NULL) + if (n->right != NULL) queue.push_back(n->right); } } -void Pre(node *n) -{ - if (n != NULL) - { +void Pre(node *n) { + if (n != NULL) { cout << n->val << " "; Pre(n->left); Pre(n->right); } } -void In(node *n) -{ - if (n != NULL) - { +void In(node *n) { + if (n != NULL) { In(n->left); cout << n->val << " "; In(n->right); } } -void Post(node *n) -{ - if (n != NULL) - { +void Post(node *n) { + if (n != NULL) { Post(n->left); Post(n->right); cout << n->val << " "; } } -int main() -{ +int main() { int value; int ch; node *root = new node; @@ -97,8 +80,7 @@ int main() root->val = value; root->left = NULL; root->right = NULL; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Breadth First"; cout << "\n3. Preorder Depth First"; @@ -107,8 +89,7 @@ int main() cout << "\nEnter Your Choice : "; cin >> ch; - switch (ch) - { + switch (ch) { case 1: int x; char pos; diff --git a/data_structure/trie_tree.cpp b/data_structure/trie_tree.cpp index 2b84099e8..66b67fbc0 100644 --- a/data_structure/trie_tree.cpp +++ b/data_structure/trie_tree.cpp @@ -1,78 +1,75 @@ -#include #include +#include #include #include // structure definition typedef struct trie { - struct trie * arr[26]; + struct trie* arr[26]; bool isEndofWord; } trie; // create a new node for trie -trie * createNode() { - trie * nn = new trie(); - for (int i = 0; i < 26; i++) - nn -> arr[i] = NULL; - nn -> isEndofWord = false; +trie* createNode() { + trie* nn = new trie(); + for (int i = 0; i < 26; i++) nn->arr[i] = NULL; + nn->isEndofWord = false; return nn; } // insert string into the trie -void insert(trie * root, std::string str) { +void insert(trie* root, std::string str) { for (int i = 0; i < str.length(); i++) { int j = str[i] - 'a'; - if (root -> arr[j]) { - root = root -> arr[j]; + if (root->arr[j]) { + root = root->arr[j]; } else { - root -> arr[j] = createNode(); - root = root -> arr[j]; + root->arr[j] = createNode(); + root = root->arr[j]; } } - root -> isEndofWord = true; + root->isEndofWord = true; } // search a string exists inside the trie -bool search(trie * root, std::string str, int index) { +bool search(trie* root, std::string str, int index) { if (index == str.length()) { - if (!root -> isEndofWord) + if (!root->isEndofWord) return false; return true; } int j = str[index] - 'a'; - if (!root -> arr[j]) + if (!root->arr[j]) return false; - return search(root -> arr[j], str, index + 1); + return search(root->arr[j], str, index + 1); } /* -removes the string if it is not a prefix of any other -string, if it is then just sets the endofword to false, else +removes the string if it is not a prefix of any other +string, if it is then just sets the endofword to false, else removes the given string */ -bool deleteString(trie * root, std::string str, int index) { +bool deleteString(trie* root, std::string str, int index) { if (index == str.length()) { - if (!root -> isEndofWord) - return false; - root -> isEndofWord = false; - for (int i = 0; i < 26; i++) + if (!root->isEndofWord) return false; + root->isEndofWord = false; + for (int i = 0; i < 26; i++) return false; return true; } int j = str[index] - 'a'; - if (!root -> arr[j]) + if (!root->arr[j]) return false; - bool - var = deleteString(root, str, index + 1); + bool var = deleteString(root, str, index + 1); if (var) { - root -> arr[j] = NULL; - if (root -> isEndofWord) { + root->arr[j] = NULL; + if (root->isEndofWord) { return false; } else { int i; for (i = 0; i < 26; i++) - if (root -> arr[i]) + if (root->arr[i]) return false; return true; } @@ -80,7 +77,7 @@ bool deleteString(trie * root, std::string str, int index) { } int main() { - trie * root = createNode(); + trie* root = createNode(); insert(root, "hello"); insert(root, "world"); int a = search(root, "hello", 0); diff --git a/dynamic_programming/0-1 Knapsack.cpp b/dynamic_programming/0-1 Knapsack.cpp deleted file mode 100644 index 9348372b2..000000000 --- a/dynamic_programming/0-1 Knapsack.cpp +++ /dev/null @@ -1,71 +0,0 @@ -//0-1 Knapsack problem - Dynamic programming -//#include -#include -using namespace std; - -//void Print(int res[20][20], int i, int j, int capacity) -//{ -// if(i==0 || j==0) -// { -// return; -// } -// if(res[i-1][j]==res[i][j-1]) -// { -// if(i<=capacity) -// { -// cout<res[i][j-1]) -// { -// Print(res, i-1,j, capacity); -// } -// else if(res[i][j-1]>res[i-1][j]) -// { -// Print(res, i,j-1, capacity); -// } -//} - -int Knapsack(int capacity, int n, int weight[], int value[]) -{ - int res[20][20]; - for (int i = 0; i < n + 1; ++i) - { - for (int j = 0; j < capacity + 1; ++j) - { - if (i == 0 || j == 0) - res[i][j] = 0; - else if (weight[i - 1] <= j) - res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]); - else - res[i][j] = res[i - 1][j]; - } - } - // Print(res, n, capacity, capacity); - // cout<<"\n"; - return res[n][capacity]; -} -int main() -{ - int n; - cout << "Enter number of items: "; - cin >> n; - int weight[n], value[n]; - cout << "Enter weights: "; - for (int i = 0; i < n; ++i) - { - cin >> weight[i]; - } - cout << "Enter values: "; - for (int i = 0; i < n; ++i) - { - cin >> value[i]; - } - int capacity; - cout << "Enter capacity: "; - cin >> capacity; - cout << Knapsack(capacity, n, weight, value); - return 0; -} diff --git a/dynamic_programming/0_1_knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp new file mode 100644 index 000000000..7ea0c04c6 --- /dev/null +++ b/dynamic_programming/0_1_knapsack.cpp @@ -0,0 +1,66 @@ +// 0-1 Knapsack problem - Dynamic programming +//#include +#include +using namespace std; + +// void Print(int res[20][20], int i, int j, int capacity) +//{ +// if(i==0 || j==0) +// { +// return; +// } +// if(res[i-1][j]==res[i][j-1]) +// { +// if(i<=capacity) +// { +// cout<res[i][j-1]) +// { +// Print(res, i-1,j, capacity); +// } +// else if(res[i][j-1]>res[i-1][j]) +// { +// Print(res, i,j-1, capacity); +// } +//} + +int Knapsack(int capacity, int n, int weight[], int value[]) { + int res[20][20]; + for (int i = 0; i < n + 1; ++i) { + for (int j = 0; j < capacity + 1; ++j) { + if (i == 0 || j == 0) + res[i][j] = 0; + else if (weight[i - 1] <= j) + res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], + res[i - 1][j]); + else + res[i][j] = res[i - 1][j]; + } + } + // Print(res, n, capacity, capacity); + // cout<<"\n"; + return res[n][capacity]; +} +int main() { + int n; + cout << "Enter number of items: "; + cin >> n; + int weight[n], value[n]; + cout << "Enter weights: "; + for (int i = 0; i < n; ++i) { + cin >> weight[i]; + } + cout << "Enter values: "; + for (int i = 0; i < n; ++i) { + cin >> value[i]; + } + int capacity; + cout << "Enter capacity: "; + cin >> capacity; + cout << Knapsack(capacity, n, weight, value); + return 0; +} diff --git a/dynamic_programming/Bellman-Ford.cpp b/dynamic_programming/Bellman-Ford.cpp deleted file mode 100644 index 7c36d96df..000000000 --- a/dynamic_programming/Bellman-Ford.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include -#include - -using namespace std; - -//Wrapper class for storing an edge -class Edge -{ -public: - int src, dst, weight; -}; - -//Wrapper class for storing a graph -class Graph -{ -public: - int vertexNum, edgeNum; - Edge *edges; - - //Constructs a graph with V vertices and E edges - Graph(int V, int E) - { - this->vertexNum = V; - this->edgeNum = E; - this->edges = (Edge *)malloc(E * sizeof(Edge)); - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { - static int edgeInd = 0; - if (edgeInd < this->edgeNum) - { - Edge newEdge; - newEdge.src = src; - newEdge.dst = dst; - newEdge.weight = weight; - this->edges[edgeInd++] = newEdge; - } - } -}; - -//Utility function to print distances -void print(int dist[], int V) -{ - cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { - if (dist[i] != INT_MAX) - cout << i << "\t" << dist[i] << endl; - else - cout << i << "\tINF" << endl; - } -} - -//The main function that finds the shortest path from given source -//to all other vertices using Bellman-Ford.It also detects negative -//weight cycle -void BellmanFord(Graph graph, int src) -{ - int V = graph.vertexNum; - int E = graph.edgeNum; - int dist[V]; - - //Initialize distances array as INF for all except source - //Intialize source as zero - for (int i = 0; i < V; i++) - dist[i] = INT_MAX; - dist[src] = 0; - - //Calculate shortest path distance from source to all edges - //A path can contain maximum (|V|-1) edges - for (int i = 0; i <= V - 1; i++) - for (int j = 0; j < E; j++) - { - int u = graph.edges[j].src; - int v = graph.edges[j].dst; - int w = graph.edges[j].weight; - - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - dist[v] = dist[u] + w; - } - - //Iterate inner loop once more to check for negative cycle - for (int j = 0; j < E; j++) - { - int u = graph.edges[j].src; - int v = graph.edges[j].dst; - int w = graph.edges[j].weight; - - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - { - cout << "Graph contains negative weight cycle. Hence, shortest distance not guaranteed." << endl; - return; - } - } - - print(dist, V); - - return; -} - -//Driver Function -int main() -{ - int V, E, gsrc; - int src, dst, weight; - cout << "Enter number of vertices: "; - cin >> V; - cout << "Enter number of edges: "; - cin >> E; - Graph G(V, E); - for (int i = 0; i < E; i++) - { - cout << "\nEdge " << i + 1 << "\nEnter source: "; - cin >> src; - cout << "Enter destination: "; - cin >> dst; - cout << "Enter weight: "; - cin >> weight; - G.addEdge(src, dst, weight); - } - cout << "\nEnter source: "; - cin >> gsrc; - BellmanFord(G, gsrc); - - return 0; -} diff --git a/dynamic_programming/Coin-Change.cpp b/dynamic_programming/Coin-Change.cpp deleted file mode 100644 index c8acad48e..000000000 --- a/dynamic_programming/Coin-Change.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include -using namespace std; - -// Function to find the Minimum number of coins required to get Sum S -int findMinCoins(int arr[], int n, int N) -{ - // dp[i] = no of coins required to get a total of i - int dp[N + 1]; - - // 0 coins are needed for 0 sum - - dp[0] = 0; - - for (int i = 1; i <= N; i++) - { - // initialize minimum number of coins needed to infinity - dp[i] = INT_MAX; - int res = INT_MAX; - - // do for each coin - for (int c = 0; c < n; c++) - { - if (i - arr[c] >= 0) // check if coins doesn't become negative by including it - res = dp[i - arr[c]]; - - // if total can be reached by including current coin c, - // update minimum number of coins needed dp[i] - if (res != INT_MAX) - dp[i] = min(dp[i], res + 1); - } - } - - // The Minimum No of Coins Required for N = dp[N] - return dp[N]; -} - -int main() -{ - // No of Coins We Have - int arr[] = {1, 2, 3, 4}; - int n = sizeof(arr) / sizeof(arr[0]); - - // Total Change Required - int N = 15; - - cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) << "\n"; - - return 0; -} \ No newline at end of file diff --git a/dynamic_programming/Cut Rod.cpp b/dynamic_programming/Cut Rod.cpp deleted file mode 100644 index afca3dced..000000000 --- a/dynamic_programming/Cut Rod.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/*Given a rod of length n inches and an array of prices that -contains prices of all pieces of size smaller than n. Determine -the maximum value obtainable by cutting up the rod and selling -the pieces.*/ - -#include -using namespace std; -int cutrod(int p[], int n) -{ - int r[n + 1]; - r[0] = 0; - for (int j = 0; j < n; j++) - { - int q = INT_MIN; - for (int i = 0; i <= j; i++) - { - q = max(q, p[i] + r[j - i]); - } - r[j + 1] = q; - } - return r[n]; -} -int main() -{ - int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; - cout << cutrod(price, 30); - return 0; -} diff --git a/dynamic_programming/Fibonacci_Bottom_Up.cpp b/dynamic_programming/Fibonacci_Bottom_Up.cpp deleted file mode 100644 index ab5b5b41f..000000000 --- a/dynamic_programming/Fibonacci_Bottom_Up.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include -using namespace std; -int fib(int n) -{ - int res[3]; - res[0] = 0; - res[1] = 1; - for (int i = 2; i <= n; i++) - { - res[2] = res[1] + res[0]; - res[0] = res[1]; - res[1] = res[2]; - } - return res[1]; -} -int main(int argc, char const *argv[]) -{ - int n; - cout << "Enter n: "; - cin >> n; - cout << "Fibonacci number is "; - cout << fib(n) << endl; - return 0; -} diff --git a/dynamic_programming/Fibonacci_Top_Down.cpp b/dynamic_programming/Fibonacci_Top_Down.cpp deleted file mode 100644 index 9d76366f7..000000000 --- a/dynamic_programming/Fibonacci_Top_Down.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include -using namespace std; -int arr[1000000]; -int fib(int n) -{ - if (arr[n] == -1) - { - if (n <= 1) - arr[n] = n; - else - arr[n] = fib(n - 1) + fib(n - 2); - } - return arr[n]; -} -int main(int argc, char const *argv[]) -{ - int n; - cout << "Enter n: "; - cin >> n; - for (int i = 0; i < n + 1; ++i) - { - arr[i] = -1; - } - cout << "Fibonacci number is " << fib(n) << endl; - return 0; -} \ No newline at end of file diff --git a/dynamic_programming/Floyd-Warshall.cpp b/dynamic_programming/Floyd-Warshall.cpp deleted file mode 100644 index 93ccff62f..000000000 --- a/dynamic_programming/Floyd-Warshall.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include -#include -#include - -using namespace std; - -//Wrapper class for storing a graph -class Graph -{ -public: - int vertexNum; - int **edges; - - //Constructs a graph with V vertices and E edges - Graph(int V) - { - this->vertexNum = V; - this->edges = (int **)malloc(V * sizeof(int *)); - for (int i = 0; i < V; i++) - { - this->edges[i] = (int *)malloc(V * sizeof(int)); - for (int j = 0; j < V; j++) - this->edges[i][j] = INT_MAX; - this->edges[i][i] = 0; - } - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { - this->edges[src][dst] = weight; - } -}; - -//Utility function to print distances -void print(int dist[], int V) -{ - cout << "\nThe Distance matrix for Floyd - Warshall" << endl; - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { - - if (dist[i * V + j] != INT_MAX) - cout << dist[i * V + j] << "\t"; - else - cout << "INF" - << "\t"; - } - cout << endl; - } -} - -//The main function that finds the shortest path from a vertex -//to all other vertices using Floyd-Warshall Algorithm. -void FloydWarshall(Graph graph) -{ - int V = graph.vertexNum; - int dist[V][V]; - - //Initialise distance array - for (int i = 0; i < V; i++) - for (int j = 0; j < V; j++) - dist[i][j] = graph.edges[i][j]; - - //Calculate distances - for (int k = 0; k < V; k++) - //Choose an intermediate vertex - - for (int i = 0; i < V; i++) - //Choose a source vertex for given intermediate - - for (int j = 0; j < V; j++) - //Choose a destination vertex for above source vertex - - if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) - //If the distance through intermediate vertex is less than direct edge then update value in distance array - dist[i][j] = dist[i][k] + dist[k][j]; - - //Convert 2d array to 1d array for print - int dist1d[V * V]; - for (int i = 0; i < V; i++) - for (int j = 0; j < V; j++) - dist1d[i * V + j] = dist[i][j]; - - print(dist1d, V); -} - -//Driver Function -int main() -{ - int V, E; - int src, dst, weight; - cout << "Enter number of vertices: "; - cin >> V; - cout << "Enter number of edges: "; - cin >> E; - Graph G(V); - for (int i = 0; i < E; i++) - { - cout << "\nEdge " << i + 1 << "\nEnter source: "; - cin >> src; - cout << "Enter destination: "; - cin >> dst; - cout << "Enter weight: "; - cin >> weight; - G.addEdge(src, dst, weight); - } - FloydWarshall(G); - - return 0; -} diff --git a/dynamic_programming/Longest Common Subsequence.cpp b/dynamic_programming/Longest Common Subsequence.cpp deleted file mode 100644 index af50720b4..000000000 --- a/dynamic_programming/Longest Common Subsequence.cpp +++ /dev/null @@ -1,82 +0,0 @@ -//Longest common subsequence - Dynamic Programming -#include -using namespace std; - -void Print(int trace[20][20], int m, int n, string a) -{ - if (m == 0 || n == 0) - { - return; - } - if (trace[m][n] == 1) - { - Print(trace, m - 1, n - 1, a); - cout << a[m - 1]; - } - else if (trace[m][n] == 2) - { - Print(trace, m - 1, n, a); - } - else if (trace[m][n] == 3) - { - Print(trace, m, n - 1, a); - } -} - -int lcs(string a, string b) -{ - int m = a.length(), n = b.length(); - int res[m + 1][n + 1]; - int trace[20][20]; - - // fills up the arrays with zeros. - for (int i = 0; i < m + 1; i++) - { - for (int j = 0; j < n + 1; j++) - { - res[i][j] = 0; - trace[i][j] = 0; - } - } - - for (int i = 0; i < m + 1; ++i) - { - for (int j = 0; j < n + 1; ++j) - { - if (i == 0 || j == 0) - { - res[i][j] = 0; - trace[i][j] = 0; - } - - else if (a[i - 1] == b[j - 1]) - { - res[i][j] = 1 + res[i - 1][j - 1]; - trace[i][j] = 1; // 1 means trace the matrix in upper left diagonal direction. - } - else - { - if (res[i - 1][j] > res[i][j - 1]) - { - res[i][j] = res[i - 1][j]; - trace[i][j] = 2; // 2 means trace the matrix in upwards direction. - } - else - { - res[i][j] = res[i][j - 1]; - trace[i][j] = 3; // means trace the matrix in left direction. - } - } - } - } - Print(trace, m, n, a); - return res[m][n]; -} - -int main() -{ - string a, b; - cin >> a >> b; - cout << lcs(a, b); - return 0; -} diff --git a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp b/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp deleted file mode 100644 index 5ee24e6a7..000000000 --- a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp +++ /dev/null @@ -1,46 +0,0 @@ -//Program to calculate length of longest increasing subsequence in an array -// in O(n log n) -// tested on : https://cses.fi/problemset/task/1145/ - -#include - -using namespace std; -int LIS(int arr[], int n) -{ - set < int > active; // The current built LIS. - active.insert(arr[0]); - // Loop through every element. - for (int i = 1; i < n; ++i) - { - auto get = active.lower_bound(arr[i]); - if (get == active.end()) - { - active.insert(arr[i]); - } // current element is the greatest so LIS increases by 1. - else - { - int val = * get; // we find the position where arr[i] will be in the LIS. If it is in the LIS already we do nothing - if (val > arr[i]) - { - // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; - active.erase(get); - active.insert(arr[i]); - } - } - } - return active.size(); // size of the LIS. -} -int main(int argc, char const * argv[]) -{ - int n; - cout << "Enter size of array: "; - cin >> n; - int a[n]; - cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { - cin >> a[i]; - } - cout << LIS(a, n) << endl; - return 0; -} diff --git a/dynamic_programming/Longest Increasing Subsequence.cpp b/dynamic_programming/Longest Increasing Subsequence.cpp deleted file mode 100644 index 49c54a941..000000000 --- a/dynamic_programming/Longest Increasing Subsequence.cpp +++ /dev/null @@ -1,39 +0,0 @@ -//Program to calculate length of longest increasing subsequence in an array -#include -using namespace std; -int LIS(int a[], int n) -{ - int lis[n]; - for (int i = 0; i < n; ++i) - { - lis[i] = 1; - } - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < i; ++j) - { - if (a[i] > a[j] && lis[i] < lis[j] + 1) - lis[i] = lis[j] + 1; - } - } - int res = 0; - for (int i = 0; i < n; ++i) - { - res = max(res, lis[i]); - } - return res; -} -int main(int argc, char const *argv[]) -{ - int n; - cout << "Enter size of array: "; - cin >> n; - int a[n]; - cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { - cin >> a[i]; - } - cout << LIS(a, n) << endl; - return 0; -} \ No newline at end of file diff --git a/dynamic_programming/Matrix-Chain-Multiplication.cpp b/dynamic_programming/Matrix-Chain-Multiplication.cpp deleted file mode 100644 index 1e885bd7e..000000000 --- a/dynamic_programming/Matrix-Chain-Multiplication.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include -using namespace std; - -#define MAX 10 - -// dp table to store the solution for already computed sub problems -int dp[MAX][MAX]; - -// Function to find the most efficient way to multiply the given sequence of matrices -int MatrixChainMultiplication(int dim[], int i, int j) -{ - // base case: one matrix - if (j <= i + 1) - return 0; - - // stores minimum number of scalar multiplications (i.e., cost) - // needed to compute the matrix M[i+1]...M[j] = M[i..j] - int min = INT_MAX; - - // if dp[i][j] is not calculated (calculate it!!) - - if (dp[i][j] == 0) - { - // take the minimum over each possible position at which the - // sequence of matrices can be split - - for (int k = i + 1; k <= j - 1; k++) - { - // recur for M[i+1]..M[k] to get a i x k matrix - int cost = MatrixChainMultiplication(dim, i, k); - - // recur for M[k+1]..M[j] to get a k x j matrix - cost += MatrixChainMultiplication(dim, k, j); - - // cost to multiply two (i x k) and (k x j) matrix - cost += dim[i] * dim[k] * dim[j]; - - if (cost < min) - min = cost; // store the minimum cost - } - dp[i][j] = min; - } - - // return min cost to multiply M[j+1]..M[j] - return dp[i][j]; -} - -// main function -int main() -{ - // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n - // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix - int dim[] = {10, 30, 5, 60}; - int n = sizeof(dim) / sizeof(dim[0]); - - // Function Calling: MatrixChainMultiplications(dimensions_array, starting, ending); - - cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) << "\n"; - - return 0; -} \ No newline at end of file diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp index 4dba89a27..270a705f7 100644 --- a/dynamic_programming/armstrong_number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -1,21 +1,21 @@ // Program to check whether a number is an armstrong number or not #include -using std::cout; using std::cin; +using std::cout; int main() { - int n, k, d, s = 0; - cout << "Enter a number:"; - cin >> n; - k = n; - while (k != 0) { - d = k % 10; - s += d * d * d; - k /= 10; - } - if (s == n) - cout << n << "is an armstrong number"; - else - cout << n << "is not an armstrong number"; + int n, k, d, s = 0; + cout << "Enter a number:"; + cin >> n; + k = n; + while (k != 0) { + d = k % 10; + s += d * d * d; + k /= 10; + } + if (s == n) + cout << n << "is an armstrong number"; + else + cout << n << "is not an armstrong number"; } diff --git a/dynamic_programming/bellman_ford.cpp b/dynamic_programming/bellman_ford.cpp new file mode 100644 index 000000000..c96f3fd8e --- /dev/null +++ b/dynamic_programming/bellman_ford.cpp @@ -0,0 +1,116 @@ +#include +#include + +using namespace std; + +// Wrapper class for storing an edge +class Edge { + public: + int src, dst, weight; +}; + +// Wrapper class for storing a graph +class Graph { + public: + int vertexNum, edgeNum; + Edge *edges; + + // Constructs a graph with V vertices and E edges + Graph(int V, int E) { + this->vertexNum = V; + this->edgeNum = E; + this->edges = (Edge *)malloc(E * sizeof(Edge)); + } + + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) { + static int edgeInd = 0; + if (edgeInd < this->edgeNum) { + Edge newEdge; + newEdge.src = src; + newEdge.dst = dst; + newEdge.weight = weight; + this->edges[edgeInd++] = newEdge; + } + } +}; + +// Utility function to print distances +void print(int dist[], int V) { + cout << "\nVertex Distance" << endl; + for (int i = 0; i < V; i++) { + if (dist[i] != INT_MAX) + cout << i << "\t" << dist[i] << endl; + else + cout << i << "\tINF" << endl; + } +} + +// The main function that finds the shortest path from given source +// to all other vertices using Bellman-Ford.It also detects negative +// weight cycle +void BellmanFord(Graph graph, int src) { + int V = graph.vertexNum; + int E = graph.edgeNum; + int dist[V]; + + // Initialize distances array as INF for all except source + // Intialize source as zero + for (int i = 0; i < V; i++) dist[i] = INT_MAX; + dist[src] = 0; + + // Calculate shortest path distance from source to all edges + // A path can contain maximum (|V|-1) edges + for (int i = 0; i <= V - 1; i++) + for (int j = 0; j < E; j++) { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; + + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + dist[v] = dist[u] + w; + } + + // Iterate inner loop once more to check for negative cycle + for (int j = 0; j < E; j++) { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; + + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) { + cout << "Graph contains negative weight cycle. Hence, shortest " + "distance not guaranteed." + << endl; + return; + } + } + + print(dist, V); + + return; +} + +// Driver Function +int main() { + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V, E); + for (int i = 0; i < E; i++) { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + cout << "\nEnter source: "; + cin >> gsrc; + BellmanFord(G, gsrc); + + return 0; +} diff --git a/dynamic_programming/Catalan-Numbers.cpp b/dynamic_programming/catalan_numbers.cpp similarity index 85% rename from dynamic_programming/Catalan-Numbers.cpp rename to dynamic_programming/catalan_numbers.cpp index 4d73cd51a..f5edaa916 100644 --- a/dynamic_programming/Catalan-Numbers.cpp +++ b/dynamic_programming/catalan_numbers.cpp @@ -9,10 +9,9 @@ #include using namespace std; -int *cat; // global array to hold catalan numbers +int *cat; // global array to hold catalan numbers -unsigned long int catalan_dp(int n) -{ +unsigned long int catalan_dp(int n) { /** Using the tabulation technique in dynamic programming, this function computes the first `n+1` Catalan numbers @@ -29,19 +28,17 @@ unsigned long int catalan_dp(int n) cat[0] = cat[1] = 1; // Compute the remaining numbers from index 2 to index n, using tabulation - for (int i = 2; i <= n; i++) - { + for (int i = 2; i <= n; i++) { cat[i] = 0; for (int j = 0; j < i; j++) - cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here + cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here } // Return the result return cat[n]; } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int n; cout << "Enter n: "; cin >> n; @@ -49,8 +46,7 @@ int main(int argc, char *argv[]) cat = new int[n + 1]; cout << "Catalan numbers from 0 to " << n << " are:\n"; - for (int i = 0; i <= n; i++) - { + for (int i = 0; i <= n; i++) { cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; // NOTE: Since `cat` is a global array, calling `catalan_dp` // repeatedly will not recompute the the values already computed diff --git a/dynamic_programming/coin_change.cpp b/dynamic_programming/coin_change.cpp new file mode 100644 index 000000000..8c8fc3dfb --- /dev/null +++ b/dynamic_programming/coin_change.cpp @@ -0,0 +1,48 @@ +#include +#include +using namespace std; + +// Function to find the Minimum number of coins required to get Sum S +int findMinCoins(int arr[], int n, int N) { + // dp[i] = no of coins required to get a total of i + int dp[N + 1]; + + // 0 coins are needed for 0 sum + + dp[0] = 0; + + for (int i = 1; i <= N; i++) { + // initialize minimum number of coins needed to infinity + dp[i] = INT_MAX; + int res = INT_MAX; + + // do for each coin + for (int c = 0; c < n; c++) { + if (i - arr[c] >= + 0) // check if coins doesn't become negative by including it + res = dp[i - arr[c]]; + + // if total can be reached by including current coin c, + // update minimum number of coins needed dp[i] + if (res != INT_MAX) + dp[i] = min(dp[i], res + 1); + } + } + + // The Minimum No of Coins Required for N = dp[N] + return dp[N]; +} + +int main() { + // No of Coins We Have + int arr[] = {1, 2, 3, 4}; + int n = sizeof(arr) / sizeof(arr[0]); + + // Total Change Required + int N = 15; + + cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) + << "\n"; + + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp new file mode 100644 index 000000000..136c78dbb --- /dev/null +++ b/dynamic_programming/cut_rod.cpp @@ -0,0 +1,25 @@ +/*Given a rod of length n inches and an array of prices that +contains prices of all pieces of size smaller than n. Determine +the maximum value obtainable by cutting up the rod and selling +the pieces.*/ + +#include +using namespace std; +int cutrod(int p[], int n) { + int r[n + 1]; + r[0] = 0; + for (int j = 0; j < n; j++) { + int q = INT_MIN; + for (int i = 0; i <= j; i++) { + q = max(q, p[i] + r[j - i]); + } + r[j + 1] = q; + } + return r[n]; +} +int main() { + int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; + cout << cutrod(price, 30); + return 0; +} diff --git a/dynamic_programming/Edit Distance.cpp b/dynamic_programming/edit_distance.cpp similarity index 60% rename from dynamic_programming/Edit Distance.cpp rename to dynamic_programming/edit_distance.cpp index 996d3272c..889b080cb 100644 --- a/dynamic_programming/Edit Distance.cpp +++ b/dynamic_programming/edit_distance.cpp @@ -7,7 +7,7 @@ * a. Insert * b. Remove * c. Replace - * All of the above operations are + * All of the above operations are * of equal cost */ @@ -15,31 +15,27 @@ #include using namespace std; -int min(int x, int y, int z) -{ - return min(min(x, y), z); -} +int min(int x, int y, int z) { return min(min(x, y), z); } /* A Naive recursive C++ program to find * minimum number of operations to convert * str1 to str2. * O(3^m) */ -int editDist(string str1, string str2, int m, int n) -{ +int editDist(string str1, string str2, int m, int n) { if (m == 0) return n; if (n == 0) return m; - //If last characters are same then continue - //for the rest of them. + // If last characters are same then continue + // for the rest of them. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); - //If last not same, then 3 possibilities - //a.Insert b.Remove c. Replace - //Get min of three and continue for rest. + // If last not same, then 3 possibilities + // a.Insert b.Remove c. Replace + // Get min of three and continue for rest. return 1 + min(editDist(str1, str2, m, n - 1), editDist(str1, str2, m - 1, n), editDist(str1, str2, m - 1, n - 1)); @@ -48,33 +44,29 @@ int editDist(string str1, string str2, int m, int n) /* A DP based program * O(m x n) */ -int editDistDP(string str1, string str2, int m, int n) -{ - - //Create Table for SubProblems +int editDistDP(string str1, string str2, int m, int n) { + // Create Table for SubProblems int dp[m + 1][n + 1]; - //Fill d[][] in bottom up manner - for (int i = 0; i <= m; i++) - { - for (int j = 0; j <= n; j++) - { - //If str1 empty. Then add all of str2 + // Fill d[][] in bottom up manner + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + // If str1 empty. Then add all of str2 if (i == 0) dp[i][j] = j; - //If str2 empty. Then add all of str1 + // If str2 empty. Then add all of str1 else if (j == 0) dp[i][j] = i; - //If character same. Recur for remaining + // If character same. Recur for remaining else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; else - dp[i][j] = 1 + min(dp[i][j - 1], //Insert - dp[i - 1][j], //Remove - dp[i - 1][j - 1] //Replace + dp[i][j] = 1 + min(dp[i][j - 1], // Insert + dp[i - 1][j], // Remove + dp[i - 1][j - 1] // Replace ); } } @@ -82,8 +74,7 @@ int editDistDP(string str1, string str2, int m, int n) return dp[m][n]; } -int main() -{ +int main() { string str1 = "sunday"; string str2 = "saturday"; diff --git a/dynamic_programming/Egg-Dropping-Puzzle.cpp b/dynamic_programming/egg_dropping_puzzle.cpp similarity index 63% rename from dynamic_programming/Egg-Dropping-Puzzle.cpp rename to dynamic_programming/egg_dropping_puzzle.cpp index a441f29cb..7a769ea47 100644 --- a/dynamic_programming/Egg-Dropping-Puzzle.cpp +++ b/dynamic_programming/egg_dropping_puzzle.cpp @@ -1,35 +1,29 @@ -/* Function to get minimun number of trials needed - * in worst case with n eggs and k floors +/* Function to get minimun number of trials needed + * in worst case with n eggs and k floors */ -#include #include +#include using namespace std; -int eggDrop(int n, int k) -{ +int eggDrop(int n, int k) { int eggFloor[n + 1][k + 1]; int result; - for (int i = 1; i <= n; i++) - { - eggFloor[i][1] = 1; //n eggs..1 Floor - eggFloor[i][0] = 0; //n eggs..0 Floor + for (int i = 1; i <= n; i++) { + eggFloor[i][1] = 1; // n eggs..1 Floor + eggFloor[i][0] = 0; // n eggs..0 Floor } // Only one egg available - for (int j = 1; j <= k; j++) - { + for (int j = 1; j <= k; j++) { eggFloor[1][j] = j; } - for (int i = 2; i <= n; i++) - { - for (int j = 2; j <= k; j++) - { + for (int i = 2; i <= n; i++) { + for (int j = 2; j <= k; j++) { eggFloor[i][j] = INT_MAX; - for (int x = 1; x <= j; x++) - { + for (int x = 1; x <= j; x++) { // 1+max(eggBreak[one less egg, lower floors], // eggDoesntBreak[same # of eggs, upper floors]); result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); @@ -42,8 +36,7 @@ int eggDrop(int n, int k) return eggFloor[n][k]; } -int main() -{ +int main() { int n, k; cout << "Enter number of eggs and floors: "; cin >> n >> k; diff --git a/dynamic_programming/fibonacci_bottom_up.cpp b/dynamic_programming/fibonacci_bottom_up.cpp new file mode 100644 index 000000000..555f15282 --- /dev/null +++ b/dynamic_programming/fibonacci_bottom_up.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +int fib(int n) { + int res[3]; + res[0] = 0; + res[1] = 1; + for (int i = 2; i <= n; i++) { + res[2] = res[1] + res[0]; + res[0] = res[1]; + res[1] = res[2]; + } + return res[1]; +} +int main(int argc, char const *argv[]) { + int n; + cout << "Enter n: "; + cin >> n; + cout << "Fibonacci number is "; + cout << fib(n) << endl; + return 0; +} diff --git a/dynamic_programming/fibonacci_top_down.cpp b/dynamic_programming/fibonacci_top_down.cpp new file mode 100644 index 000000000..3c0c9a1a3 --- /dev/null +++ b/dynamic_programming/fibonacci_top_down.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; +int arr[1000000]; +int fib(int n) { + if (arr[n] == -1) { + if (n <= 1) + arr[n] = n; + else + arr[n] = fib(n - 1) + fib(n - 2); + } + return arr[n]; +} +int main(int argc, char const *argv[]) { + int n; + cout << "Enter n: "; + cin >> n; + for (int i = 0; i < n + 1; ++i) { + arr[i] = -1; + } + cout << "Fibonacci number is " << fib(n) << endl; + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/floyd_warshall.cpp b/dynamic_programming/floyd_warshall.cpp new file mode 100644 index 000000000..d193ebbd5 --- /dev/null +++ b/dynamic_programming/floyd_warshall.cpp @@ -0,0 +1,107 @@ +#include +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +// Wrapper class for storing a graph +class Graph { + public: + int vertexNum; + int **edges; + + // Constructs a graph with V vertices and E edges + Graph(int V) { + this->vertexNum = V; + this->edges = new int *[V]; + for (int i = 0; i < V; i++) { + this->edges[i] = new int[V]; + for (int j = 0; j < V; j++) this->edges[i][j] = INT_MAX; + this->edges[i][i] = 0; + } + } + + ~Graph() { + for (int i = 0; i < vertexNum; i++) delete[] edges[i]; + delete[] edges; + } + + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) { + this->edges[src][dst] = weight; + } +}; + +// Utility function to print distances +void print(int dist[], int V) { + cout << "\nThe Distance matrix for Floyd - Warshall" << endl; + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (dist[i * V + j] != INT_MAX) + cout << dist[i * V + j] << "\t"; + else + cout << "INF" + << "\t"; + } + cout << endl; + } +} + +// The main function that finds the shortest path from a vertex +// to all other vertices using Floyd-Warshall Algorithm. +void FloydWarshall(Graph graph) { + int V = graph.vertexNum; + int dist[V][V]; + + // Initialise distance array + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) dist[i][j] = graph.edges[i][j]; + + // Calculate distances + for (int k = 0; k < V; k++) + // Choose an intermediate vertex + + for (int i = 0; i < V; i++) + // Choose a source vertex for given intermediate + + for (int j = 0; j < V; j++) + // Choose a destination vertex for above source vertex + + if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && + dist[i][k] + dist[k][j] < dist[i][j]) + // If the distance through intermediate vertex is less than + // direct edge then update value in distance array + dist[i][j] = dist[i][k] + dist[k][j]; + + // Convert 2d array to 1d array for print + int dist1d[V * V]; + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) dist1d[i * V + j] = dist[i][j]; + + print(dist1d, V); +} + +// Driver Function +int main() { + int V, E; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V); + for (int i = 0; i < E; i++) { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + FloydWarshall(G); + + return 0; +} diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp index bf2aa76ac..b5272756b 100644 --- a/dynamic_programming/kadane.cpp +++ b/dynamic_programming/kadane.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; @@ -15,7 +15,6 @@ int maxSubArraySum(int a[], int size) { return max_so_far; } - int main() { int n, i; std::cout << "Enter the number of elements \n"; diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp index c1e89d6db..81fa8a002 100644 --- a/dynamic_programming/longest_common_string.cpp +++ b/dynamic_programming/longest_common_string.cpp @@ -1,65 +1,53 @@ #include using namespace std; -int max(int a,int b) -{ - return (a > b) ? a : b; -} +int max(int a, int b) { return (a > b) ? a : b; } -int main() -{ - char str1[]="DEFBCD"; - char str2[]="ABDEFJ"; - int i,j,k; - int n=strlen(str1)+1; - int m=strlen(str2)+1; - //cout<ma) - { - ma=a[i][j]; - indi=i; - indj=j; + for(j=0;j ma) { + ma = a[i][j]; + indi = i; + indj = j; } } } - cout< +using namespace std; + +void Print(int trace[20][20], int m, int n, string a) { + if (m == 0 || n == 0) { + return; + } + if (trace[m][n] == 1) { + Print(trace, m - 1, n - 1, a); + cout << a[m - 1]; + } else if (trace[m][n] == 2) { + Print(trace, m - 1, n, a); + } else if (trace[m][n] == 3) { + Print(trace, m, n - 1, a); + } +} + +int lcs(string a, string b) { + int m = a.length(), n = b.length(); + int res[m + 1][n + 1]; + int trace[20][20]; + + // fills up the arrays with zeros. + for (int i = 0; i < m + 1; i++) { + for (int j = 0; j < n + 1; j++) { + res[i][j] = 0; + trace[i][j] = 0; + } + } + + for (int i = 0; i < m + 1; ++i) { + for (int j = 0; j < n + 1; ++j) { + if (i == 0 || j == 0) { + res[i][j] = 0; + trace[i][j] = 0; + } + + else if (a[i - 1] == b[j - 1]) { + res[i][j] = 1 + res[i - 1][j - 1]; + trace[i][j] = 1; // 1 means trace the matrix in upper left + // diagonal direction. + } else { + if (res[i - 1][j] > res[i][j - 1]) { + res[i][j] = res[i - 1][j]; + trace[i][j] = + 2; // 2 means trace the matrix in upwards direction. + } else { + res[i][j] = res[i][j - 1]; + trace[i][j] = + 3; // means trace the matrix in left direction. + } + } + } + } + Print(trace, m, n, a); + return res[m][n]; +} + +int main() { + string a, b; + cin >> a >> b; + cout << lcs(a, b); + return 0; +} diff --git a/dynamic_programming/longest_increasing_subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp new file mode 100644 index 000000000..b6a798aa0 --- /dev/null +++ b/dynamic_programming/longest_increasing_subsequence.cpp @@ -0,0 +1,32 @@ +// Program to calculate length of longest increasing subsequence in an array +#include +using namespace std; +int LIS(int a[], int n) { + int lis[n]; + for (int i = 0; i < n; ++i) { + lis[i] = 1; + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (a[i] > a[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + } + } + int res = 0; + for (int i = 0; i < n; ++i) { + res = max(res, lis[i]); + } + return res; +} +int main(int argc, char const *argv[]) { + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp new file mode 100644 index 000000000..5bc72345c --- /dev/null +++ b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp @@ -0,0 +1,41 @@ +// Program to calculate length of longest increasing subsequence in an array +// in O(n log n) +// tested on : https://cses.fi/problemset/task/1145/ + +#include + +using namespace std; +int LIS(int arr[], int n) { + set active; // The current built LIS. + active.insert(arr[0]); + // Loop through every element. + for (int i = 1; i < n; ++i) { + auto get = active.lower_bound(arr[i]); + if (get == active.end()) { + active.insert(arr[i]); + } // current element is the greatest so LIS increases by 1. + else { + int val = *get; // we find the position where arr[i] will be in the + // LIS. If it is in the LIS already we do nothing + if (val > arr[i]) { + // else we remove the bigger element and add a smaller element + // (which is arr[i]) and continue; + active.erase(get); + active.insert(arr[i]); + } + } + } + return active.size(); // size of the LIS. +} +int main(int argc, char const* argv[]) { + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; +} diff --git a/dynamic_programming/matrix_chain_multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp new file mode 100644 index 000000000..7d6647c52 --- /dev/null +++ b/dynamic_programming/matrix_chain_multiplication.cpp @@ -0,0 +1,61 @@ +#include +#include +using namespace std; + +#define MAX 10 + +// dp table to store the solution for already computed sub problems +int dp[MAX][MAX]; + +// Function to find the most efficient way to multiply the given sequence of +// matrices +int MatrixChainMultiplication(int dim[], int i, int j) { + // base case: one matrix + if (j <= i + 1) + return 0; + + // stores minimum number of scalar multiplications (i.e., cost) + // needed to compute the matrix M[i+1]...M[j] = M[i..j] + int min = INT_MAX; + + // if dp[i][j] is not calculated (calculate it!!) + + if (dp[i][j] == 0) { + // take the minimum over each possible position at which the + // sequence of matrices can be split + + for (int k = i + 1; k <= j - 1; k++) { + // recur for M[i+1]..M[k] to get a i x k matrix + int cost = MatrixChainMultiplication(dim, i, k); + + // recur for M[k+1]..M[j] to get a k x j matrix + cost += MatrixChainMultiplication(dim, k, j); + + // cost to multiply two (i x k) and (k x j) matrix + cost += dim[i] * dim[k] * dim[j]; + + if (cost < min) + min = cost; // store the minimum cost + } + dp[i][j] = min; + } + + // return min cost to multiply M[j+1]..M[j] + return dp[i][j]; +} + +// main function +int main() { + // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n + // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix + int dim[] = {10, 30, 5, 60}; + int n = sizeof(dim) / sizeof(dim[0]); + + // Function Calling: MatrixChainMultiplications(dimensions_array, starting, + // ending); + + cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) + << "\n"; + + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 9ee48dded..7792a5149 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -1,36 +1,36 @@ /* -*this program is use to find any elemet in any row with variable array size -*aplication of pointer is use in it -*important point start from here to: -*the index value of array can be go to 1 to 100000 -*check till array[1000] -*end here -*how to work example: -**Question: -***number of array 2 -***quarry 3 -***array 1 is {1 2 3 4 5} -***array 2 is {6 7} -****i) what is 2nd element in 1st array -****ii) what is 1st element in 2nd array -****iii) what is 5th element in 1st array -*****output: -*****Enter Number of array you want to Store : 2 -*****Enter Number of Question or Quary you want to do Related to Array : 3 -*****Enter number of element in 1 rows : 5 -*****Enter the element of Array 1 2 3 4 5 -*****Enter number of element in 2 rows : 2 -*****Enter the element of Array 6 7 -*****enter the number of row which element You want to find : 1 -*****enter the position of element which You want to find : 2 -*****The element is 2 -*****enter the number of row which element You want to find : 2 -*****enter the position of element which You want to find : 1 -*****The element is 6 -*****enter the number of row which element You want to find : 1 -*****enter the position of element which You want to find : 5 -*****The element is 5 -*/ + *this program is use to find any elemet in any row with variable array size + *aplication of pointer is use in it + *important point start from here to: + *the index value of array can be go to 1 to 100000 + *check till array[1000] + *end here + *how to work example: + **Question: + ***number of array 2 + ***quarry 3 + ***array 1 is {1 2 3 4 5} + ***array 2 is {6 7} + ****i) what is 2nd element in 1st array + ****ii) what is 1st element in 2nd array + ****iii) what is 5th element in 1st array + *****output: + *****Enter Number of array you want to Store : 2 + *****Enter Number of Question or Quary you want to do Related to Array : 3 + *****Enter number of element in 1 rows : 5 + *****Enter the element of Array 1 2 3 4 5 + *****Enter number of element in 2 rows : 2 + *****Enter the element of Array 6 7 + *****enter the number of row which element You want to find : 1 + *****enter the position of element which You want to find : 2 + *****The element is 2 + *****enter the number of row which element You want to find : 2 + *****enter the position of element which You want to find : 1 + *****The element is 6 + *****enter the number of row which element You want to find : 1 + *****enter the position of element which You want to find : 5 + *****The element is 5 + */ #include // this is main fuction @@ -46,7 +46,7 @@ int main() { // create a Array in run time because use can // change the size of each array which he/she is going to store // create a 2D array - int** ar = new int* [x](); + int** ar = new int*[x](); // this for loop is use for entering different variable size array // *** for (r = 0; r < x; r++) { @@ -75,6 +75,6 @@ int main() { std::cin >> q1; q1 = q1 - 1; // use this to find desire position of element in desire array - std::cout <<"The element is "<< ar[r1][q1] < -#include +#include +#include // global declarations // no of nodes max limit. @@ -37,7 +37,7 @@ void depth_first_search(int u) { depth_first_search(v); // select maximum sub-tree height from all children. - child_height = std::max(child_height, dp[v]+1); + child_height = std::max(child_height, dp[v] + 1); } } // assigned the max child height to current visited node. @@ -61,9 +61,9 @@ int main() { adj[v].push_back(u); } // initialize all nodes as unvisited. - visited.assign(number_of_nodes+1, false); + visited.assign(number_of_nodes + 1, false); // initialize depth of all nodes to 0. - dp.assign(number_of_nodes+1, 0); + dp.assign(number_of_nodes + 1, 0); // function call which will initialize the height of all nodes. depth_first_search(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; diff --git a/graph/BFS.cpp b/graph/BFS.cpp deleted file mode 100644 index e4e12886b..000000000 --- a/graph/BFS.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include -using namespace std; -class graph -{ - int v; - list *adj; - -public: - graph(int v); - void addedge(int src, int dest); - void printgraph(); - void bfs(int s); -}; -graph::graph(int v) -{ - this->v = v; - this->adj = new list[v]; -} -void graph::addedge(int src, int dest) -{ - src--; - dest--; - adj[src].push_back(dest); - //adj[dest].push_back(src); -} -void graph::printgraph() -{ - for (int i = 0; i < this->v; i++) - { - cout << "Adjacency list of vertex " << i + 1 << " is \n"; - list::iterator it; - for (it = adj[i].begin(); it != adj[i].end(); ++it) - { - cout << *it + 1 << " "; - } - cout << endl; - } -} -void graph::bfs(int s) -{ - bool *visited = new bool[this->v + 1]; - memset(visited, false, sizeof(bool) * (this->v + 1)); - visited[s] = true; - list q; - q.push_back(s); - list::iterator it; - while (!q.empty()) - { - int u = q.front(); - cout << u << " "; - q.pop_front(); - for (it = adj[u].begin(); it != adj[u].end(); ++it) - { - if (visited[*it] == false) - { - visited[*it] = true; - q.push_back(*it); - } - } - } -} -int main() -{ - graph g(4); - g.addedge(1, 2); - g.addedge(2, 3); - g.addedge(3, 4); - g.addedge(1, 4); - g.addedge(1, 3); - //g.printgraph(); - g.bfs(2); - return 0; -} diff --git a/graph/DFS.cpp b/graph/DFS.cpp deleted file mode 100644 index 656711ac8..000000000 --- a/graph/DFS.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include -using namespace std; -int v = 4; -void DFSUtil_(int graph[4][4], bool visited[], int s) -{ - visited[s] = true; - cout << s << " "; - for (int i = 0; i < v; i++) - { - if (graph[s][i] == 1 && visited[i] == false) - { - DFSUtil_(graph, visited, i); - } - } -} - -void DFS_(int graph[4][4], int s) -{ - bool visited[v]; - memset(visited, 0, sizeof(visited)); - DFSUtil_(graph, visited, s); -} - -int main() -{ - int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; - cout << "DFS: "; - DFS_(graph, 2); - cout << endl; - return 0; -} \ No newline at end of file diff --git a/graph/Kruskal.cpp b/graph/Kruskal.cpp deleted file mode 100644 index 21b04ce49..000000000 --- a/graph/Kruskal.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include -//#include -//using namespace boost::multiprecision; -const int mx = 1e6 + 5; -const long int inf = 2e9; -typedef long long ll; -#define rep(i, n) for (i = 0; i < n; i++) -#define repp(i, a, b) for (i = a; i <= b; i++) -#define pii pair -#define vpii vector -#define vi vector -#define vll vector -#define r(x) scanf("%d", &x) -#define rs(s) scanf("%s", s) -#define gc getchar_unlocked -#define pc putchar_unlocked -#define mp make_pair -#define pb push_back -#define lb lower_bound -#define ub upper_bound -#define endl "\n" -#define fast \ - ios_base::sync_with_stdio(false); \ - cin.tie(NULL); \ - cout.tie(NULL); -using namespace std; -void in(int &x) -{ - register int c = gc(); - x = 0; - int neg = 0; - for (; ((c < 48 || c > 57) && c != '-'); c = gc()) - ; - if (c == '-') - { - neg = 1; - c = gc(); - } - for (; c > 47 && c < 58; c = gc()) - { - x = (x << 1) + (x << 3) + c - 48; - } - if (neg) - x = -x; -} -void out(int n) -{ - int N = n, rev, count = 0; - rev = N; - if (N == 0) - { - pc('0'); - return; - } - while ((rev % 10) == 0) - { - count++; - rev /= 10; - } - rev = 0; - while (N != 0) - { - rev = (rev << 3) + (rev << 1) + N % 10; - N /= 10; - } - while (rev != 0) - { - pc(rev % 10 + '0'); - rev /= 10; - } - while (count--) - pc('0'); -} -ll parent[mx], arr[mx], node, edge; -vector>> v; -void initial() -{ - int i; - rep(i, node + edge) - parent[i] = i; -} -int root(int i) -{ - while (parent[i] != i) - { - parent[i] = parent[parent[i]]; - i = parent[i]; - } - return i; -} -void join(int x, int y) -{ - int root_x = root(x); //Disjoint set union by rank - int root_y = root(y); - parent[root_x] = root_y; -} -ll kruskal() -{ - ll mincost = 0, i, x, y; - rep(i, edge) - { - x = v[i].second.first; - y = v[i].second.second; - if (root(x) != root(y)) - { - mincost += v[i].first; - join(x, y); - } - } - return mincost; -} -int main() -{ - fast; - while (1) - { - int i, j, from, to, cost, totalcost = 0; - cin >> node >> edge; //Enter the nodes and edges - if (node == 0 && edge == 0) - break; //Enter 0 0 to break out - initial(); //Initialise the parent array - rep(i, edge) - { - cin >> from >> to >> cost; - v.pb(mp(cost, mp(from, to))); - totalcost += cost; - } - sort(v.begin(), v.end()); - // rep(i,v.size()) - // cout< -#include -#include -using namespace std; - -int n, m; // For number of Vertices (V) and number of edges (E) -vector> G; -vector visited; -vector ans; - -void dfs(int v) -{ - visited[v] = true; - for (int u : G[v]) - { - if (!visited[u]) - dfs(u); - } - ans.push_back(v); -} - -void topological_sort() -{ - visited.assign(n, false); - ans.clear(); - for (int i = 0; i < n; ++i) - { - if (!visited[i]) - dfs(i); - } - reverse(ans.begin(), ans.end()); -} -int main() -{ - cout << "Enter the number of vertices and the number of directed edges\n"; - cin >> n >> m; - int x, y; - G.resize(n, vector()); - for (int i = 0; i < n; ++i) - { - cin >> x >> y; - x--, y--; // to convert 1-indexed to 0-indexed - G[x].push_back(y); - } - topological_sort(); - cout << "Topological Order : \n"; - for (int v : ans) - { - cout << v + 1 << ' '; // converting zero based indexing back to one based. - } - cout << '\n'; - return 0; -} diff --git a/graph/bfs.cpp b/graph/bfs.cpp new file mode 100644 index 000000000..3acee8f80 --- /dev/null +++ b/graph/bfs.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; +class graph { + int v; + list *adj; + + public: + graph(int v); + void addedge(int src, int dest); + void printgraph(); + void bfs(int s); +}; +graph::graph(int v) { + this->v = v; + this->adj = new list[v]; +} +void graph::addedge(int src, int dest) { + src--; + dest--; + adj[src].push_back(dest); + // adj[dest].push_back(src); +} +void graph::printgraph() { + for (int i = 0; i < this->v; i++) { + cout << "Adjacency list of vertex " << i + 1 << " is \n"; + list::iterator it; + for (it = adj[i].begin(); it != adj[i].end(); ++it) { + cout << *it + 1 << " "; + } + cout << endl; + } +} +void graph::bfs(int s) { + bool *visited = new bool[this->v + 1]; + memset(visited, false, sizeof(bool) * (this->v + 1)); + visited[s] = true; + list q; + q.push_back(s); + list::iterator it; + while (!q.empty()) { + int u = q.front(); + cout << u << " "; + q.pop_front(); + for (it = adj[u].begin(); it != adj[u].end(); ++it) { + if (visited[*it] == false) { + visited[*it] = true; + q.push_back(*it); + } + } + } +} +int main() { + graph g(4); + g.addedge(1, 2); + g.addedge(2, 3); + g.addedge(3, 4); + g.addedge(1, 4); + g.addedge(1, 3); + // g.printgraph(); + g.bfs(2); + return 0; +} diff --git a/graph/bridge_finding_with_tarjan_algorithm.cpp b/graph/bridge_finding_with_tarjan_algorithm.cpp index ca124f512..eec176af5 100644 --- a/graph/bridge_finding_with_tarjan_algorithm.cpp +++ b/graph/bridge_finding_with_tarjan_algorithm.cpp @@ -4,27 +4,27 @@ * Last Modified Date: May 24, 2020 * */ -#include // for std::vector #include // for min & max -#include // for cout -using std::vector; +#include // for cout +#include // for std::vector using std::cout; using std::min; +using std::vector; class Solution { - vector < vector < int > > graph; - vectorin_time , out_time; + vector> graph; + vector in_time, out_time; int timer; - vector < vector < int > > bridge; - vectorvisited; - void dfs(int current_node , int parent) { + vector> bridge; + vector visited; + void dfs(int current_node, int parent) { visited.at(current_node) = true; in_time[current_node] = out_time[current_node] = timer++; - for ( auto&itr : graph[current_node] ) { + for (auto& itr : graph[current_node]) { if (itr == parent) { continue; } if (!visited[itr]) { - dfs(itr , current_node); + dfs(itr, current_node); if (out_time[itr] > in_time[current_node]) { bridge.push_back({itr, current_node}); } @@ -34,14 +34,14 @@ class Solution { } public: - vector > search_bridges(int n, - const vector>& connections) { + vector> search_bridges(int n, + const vector>& connections) { timer = 0; graph.resize(n); in_time.assign(n, 0); visited.assign(n, false); out_time.assign(n, 0); - for (auto&itr : connections) { + for (auto& itr : connections) { graph.at(itr[0]).push_back(itr[1]); graph.at(itr[1]).push_back(itr[0]); } @@ -52,7 +52,7 @@ class Solution { int main(void) { Solution s1; int number_of_node = 5; - vector< vector >node; + vector> node; node.push_back({0, 1}); node.push_back({1, 3}); node.push_back({1, 2}); @@ -66,13 +66,13 @@ int main(void) { * 3 4 * * In this graph there are 4 bridges [0,2] , [2,4] , [3,5] , [1,2] - * + * * I assumed that the graph is bi-directional and connected. * */ - vector< vector > bridges = s1.search_bridges(number_of_node , node); + vector> bridges = s1.search_bridges(number_of_node, node); cout << bridges.size() << " bridges found!\n"; - for (auto&itr : bridges) { + for (auto& itr : bridges) { cout << itr[0] << " --> " << itr[1] << '\n'; } return 0; diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index 9c22cc35e..0bfb8bbdb 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -8,48 +8,47 @@ class graph { vector> adj; int connected_components; void depth_first_search(); - void explore(int, vector&); + void explore(int, vector &); + public: - explicit graph(int n): adj(n, vector()) { - connected_components = 0; - } + explicit graph(int n) : adj(n, vector()) { connected_components = 0; } void addEdge(int, int); int getConnectedComponents() { - depth_first_search(); - return connected_components; + depth_first_search(); + return connected_components; } }; void graph::addEdge(int u, int v) { - adj[u-1].push_back(v-1); - adj[v-1].push_back(u-1); + adj[u - 1].push_back(v - 1); + adj[v - 1].push_back(u - 1); } void graph::depth_first_search() { - int n = adj.size(); - vector visited(n, false); + int n = adj.size(); + vector visited(n, false); - for (int i = 0 ; i < n ; i++) { - if (!visited[i]) { - explore(i, visited); - connected_components++; + for (int i = 0; i < n; i++) { + if (!visited[i]) { + explore(i, visited); + connected_components++; + } } - } } void graph::explore(int u, vector &visited) { - visited[u] = true; - for (auto v : adj[u]) { - if (!visited[v]) { - explore(v, visited); + visited[u] = true; + for (auto v : adj[u]) { + if (!visited[v]) { + explore(v, visited); + } } - } } int main() { - graph g(4); - g.addEdge(1, 2); - g.addEdge(3, 2); - std::cout << g.getConnectedComponents(); - return 0; + graph g(4); + g.addEdge(1, 2); + g.addEdge(3, 2); + std::cout << g.getConnectedComponents(); + return 0; } diff --git a/graph/connected_components_with_dsu.cpp b/graph/connected_components_with_dsu.cpp index 2c5c6dab5..aa03bef8f 100644 --- a/graph/connected_components_with_dsu.cpp +++ b/graph/connected_components_with_dsu.cpp @@ -1,6 +1,6 @@ #include -#include #include +#include int N; // denotes number of nodes; std::vector parent; @@ -31,8 +31,7 @@ void union_sets(int a, int b) { // To join 2 components to belong to one int no_of_connected_components() { // To find total no of connected components std::set temp; // temp set to count number of connected components - for (int i = 1; i <= N; i++) - temp.insert(find_set(i)); + for (int i = 1; i <= N; i++) temp.insert(find_set(i)); return temp.size(); } diff --git a/graph/dfs.cpp b/graph/dfs.cpp new file mode 100644 index 000000000..2d38c8725 --- /dev/null +++ b/graph/dfs.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +int v = 4; +void DFSUtil_(int graph[4][4], bool visited[], int s) { + visited[s] = true; + cout << s << " "; + for (int i = 0; i < v; i++) { + if (graph[s][i] == 1 && visited[i] == false) { + DFSUtil_(graph, visited, i); + } + } +} + +void DFS_(int graph[4][4], int s) { + bool visited[v]; + memset(visited, 0, sizeof(visited)); + DFSUtil_(graph, visited, s); +} + +int main() { + int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; + cout << "DFS: "; + DFS_(graph, 2); + cout << endl; + return 0; +} \ No newline at end of file diff --git a/graph/DFS_with_stack.cc b/graph/dfs_with_stack.cpp similarity index 74% rename from graph/DFS_with_stack.cc rename to graph/dfs_with_stack.cpp index cc67c7509..193f3f291 100644 --- a/graph/DFS_with_stack.cc +++ b/graph/dfs_with_stack.cpp @@ -11,8 +11,7 @@ using namespace std; int checked[999] = {WHITE}; -void dfs(const list lista[], int start) -{ +void dfs(const list lista[], int start) { stack stack; int checked[999] = {WHITE}; @@ -20,33 +19,28 @@ void dfs(const list lista[], int start) stack.push(start); checked[start] = GREY; - while (!stack.empty()) - { + while (!stack.empty()) { int act = stack.top(); stack.pop(); - if (checked[act] == GREY) - { + if (checked[act] == GREY) { cout << act << ' '; - for (auto it = lista[act].begin(); it != lista[act].end(); ++it) - { + for (auto it = lista[act].begin(); it != lista[act].end(); ++it) { stack.push(*it); if (checked[*it] != BLACK) checked[*it] = GREY; } - checked[act] = BLACK; //nodo controllato + checked[act] = BLACK; // nodo controllato } } } -int main() -{ +int main() { int u, w; int n; cin >> n; list lista[INF]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> u >> w; lista[u].push_back(w); } diff --git a/graph/Dijkstra.cpp b/graph/dijkstra.cpp similarity index 67% rename from graph/Dijkstra.cpp rename to graph/dijkstra.cpp index b3ee44c41..650f0cd51 100644 --- a/graph/Dijkstra.cpp +++ b/graph/dijkstra.cpp @@ -1,49 +1,46 @@ -#include -#include #include #include +#include +#include using namespace std; #define INF 10000010 vector> graph[5 * 100001]; int dis[5 * 100001]; -int dij(vector> *v, int s, int *dis) -{ - priority_queue, vector>, greater>> pq; +int dij(vector> *v, int s, int *dis) { + priority_queue, vector>, + greater>> + pq; // source distance to zero. pq.push(make_pair(0, s)); dis[s] = 0; int u; - while (!pq.empty()) - { + while (!pq.empty()) { u = (pq.top()).second; pq.pop(); - for (vector>::iterator it = v[u].begin(); it != v[u].end(); it++) - { - if (dis[u] + it->first < dis[it->second]) - { + for (vector>::iterator it = v[u].begin(); + it != v[u].end(); it++) { + if (dis[u] + it->first < dis[it->second]) { dis[it->second] = dis[u] + it->first; pq.push(make_pair(dis[it->second], it->second)); } } } } -int main() -{ +int main() { int m, n, l, x, y, s; // n--> number of nodes , m --> number of edges cin >> n >> m; - for (int i = 0; i < m; i++) - { + for (int i = 0; i < m; i++) { // input edges. scanf("%d%d%d", &x, &y, &l); graph[x].push_back(make_pair(l, y)); - graph[y].push_back(make_pair(l, x)); // comment this line for directed graph + graph[y].push_back( + make_pair(l, x)); // comment this line for directed graph } // start node. scanf("%d", &s); // intialise all distances to infinity. - for (int i = 1; i <= n; i++) - dis[i] = INF; + for (int i = 1; i <= n; i++) dis[i] = INF; dij(graph, s, dis); for (int i = 1; i <= n; i++) diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp index 2e66f131f..00c9d7ca0 100644 --- a/graph/kosaraju.cpp +++ b/graph/kosaraju.cpp @@ -1,134 +1,121 @@ -/* Implementation of Kosaraju's Algorithm to find out the strongly connected components (SCCs) in a graph. - Author:Anirban166 -*/ +/* Implementation of Kosaraju's Algorithm to find out the strongly connected + components (SCCs) in a graph. Author:Anirban166 +*/ -#include -#include +#include +#include using namespace std; /** -* Iterative function/method to print graph: -* @param a[] : array of vectors (2D) -* @param V : vertices -* @return void -**/ -void print(vector a[],int V) -{ - for(int i=0;i"; - for(int j=0;j a[], int V) { + for (int i = 0; i < V; i++) { + if (!a[i].empty()) + cout << "i=" << i << "-->"; + for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " "; + if (!a[i].empty()) + cout << endl; } } /** -* //Recursive function/method to push vertices into stack passed as parameter: -* @param v : vertices -* @param &st : stack passed by reference -* @param vis[] : array to keep track of visited nodes (boolean type) -* @param adj[] : array of vectors to represent graph -* @return void -**/ -void push_vertex(int v,stack &st,bool vis[],vector adj[]) -{ - vis[v]=true; - for(auto i=adj[v].begin();i!=adj[v].end();i++) - { - if(vis[*i]==false) - push_vertex(*i,st,vis,adj); + * //Recursive function/method to push vertices into stack passed as parameter: + * @param v : vertices + * @param &st : stack passed by reference + * @param vis[] : array to keep track of visited nodes (boolean type) + * @param adj[] : array of vectors to represent graph + * @return void + **/ +void push_vertex(int v, stack &st, bool vis[], vector adj[]) { + vis[v] = true; + for (auto i = adj[v].begin(); i != adj[v].end(); i++) { + if (vis[*i] == false) + push_vertex(*i, st, vis, adj); } st.push(v); } - /** -* //Recursive function/method to implement depth first traversal(dfs): -* @param v : vertices -* @param vis[] : array to keep track of visited nodes (boolean type) -* @param grev[] : graph with reversed edges -* @return void -**/ -void dfs(int v,bool vis[],vector grev[]) -{ - vis[v]=true; + * //Recursive function/method to implement depth first traversal(dfs): + * @param v : vertices + * @param vis[] : array to keep track of visited nodes (boolean type) + * @param grev[] : graph with reversed edges + * @return void + **/ +void dfs(int v, bool vis[], vector grev[]) { + vis[v] = true; // cout<0)) - i.e. it returns the count of (number of) strongly connected components (SCCs) in the graph. (variable 'count_scc' within function) +* @return int ( 0, 1, 2..and so on, only unsigned values as either there can be +no SCCs i.e. none(0) or there will be x no. of SCCs (x>0)) i.e. it returns the +count of (number of) strongly connected components (SCCs) in the graph. +(variable 'count_scc' within function) **/ -int kosaraju(int V, vector adj[]) -{ - bool vis[V]={}; +int kosaraju(int V, vector adj[]) { + bool vis[V] = {}; stack st; - for(int v=0;v grev[V]; - for(int i=0;i 57) && c != '-'); c = gc()) + ; + if (c == '-') { + neg = 1; + c = gc(); + } + for (; c > 47 && c < 58; c = gc()) { + x = (x << 1) + (x << 3) + c - 48; + } + if (neg) + x = -x; +} +void out(int n) { + int N = n, rev, count = 0; + rev = N; + if (N == 0) { + pc('0'); + return; + } + while ((rev % 10) == 0) { + count++; + rev /= 10; + } + rev = 0; + while (N != 0) { + rev = (rev << 3) + (rev << 1) + N % 10; + N /= 10; + } + while (rev != 0) { + pc(rev % 10 + '0'); + rev /= 10; + } + while (count--) pc('0'); +} +ll parent[mx], arr[mx], node, edge; +vector>> v; +void initial() { + int i; + rep(i, node + edge) parent[i] = i; +} +int root(int i) { + while (parent[i] != i) { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + return i; +} +void join(int x, int y) { + int root_x = root(x); // Disjoint set union by rank + int root_y = root(y); + parent[root_x] = root_y; +} +ll kruskal() { + ll mincost = 0, i, x, y; + rep(i, edge) { + x = v[i].second.first; + y = v[i].second.second; + if (root(x) != root(y)) { + mincost += v[i].first; + join(x, y); + } + } + return mincost; +} +int main() { + fast; + while (1) { + int i, j, from, to, cost, totalcost = 0; + cin >> node >> edge; // Enter the nodes and edges + if (node == 0 && edge == 0) + break; // Enter 0 0 to break out + initial(); // Initialise the parent array + rep(i, edge) { + cin >> from >> to >> cost; + v.pb(mp(cost, mp(from, to))); + totalcost += cost; + } + sort(v.begin(), v.end()); + // rep(i,v.size()) + // cout< adj[N]; // Graph - int up[LG][N]; // build this table - int level[N]; // get the levels of all of them + vector adj[N]; // Graph + int up[LG][N]; // build this table + int level[N]; // get the levels of all of them - lca(int n_): n(n_) - { + lca(int n_) : n(n_) { memset(up, -1, sizeof(up)); memset(level, 0, sizeof(level)); - for (int i = 0; i < n - 1; ++i) - { + for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; a--; @@ -31,77 +28,59 @@ struct lca dfs(0, -1); build(); } - void verify() - { - for (int i = 0; i < n; ++i) - { + void verify() { + for (int i = 0; i < n; ++i) { cout << i << " : level: " << level[i] << endl; } cout << endl; - for (int i = 0; i < LG; ++i) - { + for (int i = 0; i < LG; ++i) { cout << "Power:" << i << ": "; - for (int j = 0; j < n; ++j) - { + for (int j = 0; j < n; ++j) { cout << up[i][j] << " "; } cout << endl; } } - void build() - { - for (int i = 1; i < LG; ++i) - { - for (int j = 0; j < n; ++j) - { - if (up[i - 1][j] != -1) - { + void build() { + for (int i = 1; i < LG; ++i) { + for (int j = 0; j < n; ++j) { + if (up[i - 1][j] != -1) { up[i][j] = up[i - 1][up[i - 1][j]]; } } } } - void dfs(int node, int par) - { + void dfs(int node, int par) { up[0][node] = par; - for (auto i: adj[node]) - { - if (i != par) - { + for (auto i : adj[node]) { + if (i != par) { level[i] = level[node] + 1; dfs(i, node); } } } - int query(int u, int v) - { + int query(int u, int v) { u--; v--; - if (level[v] > level[u]) - { + if (level[v] > level[u]) { swap(u, v); } // u is at the bottom. int dist = level[u] - level[v]; // Go up this much distance - for (int i = LG - 1; i >= 0; --i) - { - if (dist & (1 << i)) - { + for (int i = LG - 1; i >= 0; --i) { + if (dist & (1 << i)) { u = up[i][u]; } } - if (u == v) - { + if (u == v) { return u; } assert(level[u] == level[v]); - for (int i = LG - 1; i >= 0; --i) - { - if (up[i][u] != up[i][v]) - { + for (int i = LG - 1; i >= 0; --i) { + if (up[i][u] != up[i][v]) { u = up[i][u]; v = up[i][v]; } @@ -111,10 +90,9 @@ struct lca } }; -int main() -{ - int n; // number of nodes in the tree. - lca l(n); // will take the input in the format given +int main() { + int n; // number of nodes in the tree. + lca l(n); // will take the input in the format given // n-1 edges of the form // a b // Use verify function to see. diff --git a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp index ee394d9f0..cbd6bc15c 100644 --- a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp +++ b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp @@ -4,15 +4,15 @@ * Copyright: 2020, Open-Source * Last Modified: May 25, 2020 */ -#include -#include -#include #include #include -#include #include -#include +#include +#include +#include +#include #include +#include // std::max capacity of node in graph const int MAXN = 505; class Graph { @@ -21,13 +21,13 @@ class Graph { int total_nodes; int total_edges, source, sink; int parent[MAXN]; - std::vector >edge_participated; - std::bitset visited; + std::vector > edge_participated; + std::bitset visited; int max_flow = 0; bool bfs(int source, int sink) { // to find the augmented - path memset(parent, -1, sizeof(parent)); visited.reset(); - std::queueq; + std::queue q; q.push(source); bool is_path_found = false; while (q.empty() == false && is_path_found == false) { @@ -49,9 +49,7 @@ class Graph { } public: - Graph() { - memset(residual_capacity, 0, sizeof(residual_capacity)); - } + Graph() { memset(residual_capacity, 0, sizeof(residual_capacity)); } void set_graph(void) { std::cin >> total_nodes >> total_edges >> source >> sink; for (int start, destination, capacity_, i = 0; i < total_edges; ++i) { @@ -71,7 +69,7 @@ class Graph { } current_node = sink; max_flow += flow; - while ( current_node != source ) { + while (current_node != source) { int parent_ = parent[current_node]; residual_capacity[parent_][current_node] -= flow; residual_capacity[current_node][parent_] += flow; @@ -83,23 +81,21 @@ class Graph { for (int i = 0; i < total_nodes; ++i) { for (int j = 0; j < total_nodes; ++j) { if (capacity[i][j] && - residual_capacity[i][j] < capacity[i][j]) { - edge_participated.push_back( - std::make_tuple(i, j, - capacity[i][j]-residual_capacity[i][j])); + residual_capacity[i][j] < capacity[i][j]) { + edge_participated.push_back(std::make_tuple( + i, j, capacity[i][j] - residual_capacity[i][j])); } } } - std::cout << "\nNodes : " << total_nodes - << "\nMax flow: " << max_flow - << "\nEdge present in flow: " << edge_participated.size() - << '\n'; - std::cout<< "\nSource\tDestination\tCapacity\total_nodes"; - for (auto&edge_data : edge_participated) { + std::cout << "\nNodes : " << total_nodes << "\nMax flow: " << max_flow + << "\nEdge present in flow: " << edge_participated.size() + << '\n'; + std::cout << "\nSource\tDestination\tCapacity\total_nodes"; + for (auto& edge_data : edge_participated) { int source, destination, capacity_; std::tie(source, destination, capacity_) = edge_data; - std::cout << source << "\t" << destination << "\t\t" - << capacity_ <<'\t'; + std::cout << source << "\t" << destination << "\t\t" << capacity_ + << '\t'; } } }; @@ -119,4 +115,3 @@ int main(void) { graph.print_flow_info(); return 0; } - diff --git a/graph/prim.cpp b/graph/prim.cpp index 2923b5b25..5cc70bd39 100644 --- a/graph/prim.cpp +++ b/graph/prim.cpp @@ -1,22 +1,22 @@ // C++ program to implement Prim's Algorithm #include -#include #include +#include const int MAX = 1e4 + 5; -typedef std:: pair PII; +typedef std::pair PII; bool marked[MAX]; -std:: vector adj[MAX]; +std::vector adj[MAX]; int prim(int x) { // priority queue to maintain edges with respect to weights - std:: priority_queue, std:: greater > Q; + std::priority_queue, std::greater > Q; int y; int minimumCost = 0; PII p; - Q.push(std:: make_pair(0, x)); + Q.push(std::make_pair(0, x)); while (!Q.empty()) { // Select the edge with minimum weight p = Q.top(); @@ -40,19 +40,19 @@ int main() { int nodes, edges, x, y; int weight, minimumCost; - std:: cin >> nodes >> edges; // number of nodes & edges in graph + std::cin >> nodes >> edges; // number of nodes & edges in graph if (nodes == 0 || edges == 0) return 0; // Edges with their nodes & weight for (int i = 0; i < edges; ++i) { std::cin >> x >> y >> weight; - adj[x].push_back(std:: make_pair(weight, y)); - adj[y].push_back(std:: make_pair(weight, x)); + adj[x].push_back(std::make_pair(weight, y)); + adj[y].push_back(std::make_pair(weight, x)); } // Selecting 1 as the starting node minimumCost = prim(1); - std:: cout << minimumCost << std:: endl; + std::cout << minimumCost << std::endl; return 0; } diff --git a/graph/topological_sort.cpp b/graph/topological_sort.cpp new file mode 100644 index 000000000..9e6c8917b --- /dev/null +++ b/graph/topological_sort.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +int n, m; // For number of Vertices (V) and number of edges (E) +vector> G; +vector visited; +vector ans; + +void dfs(int v) { + visited[v] = true; + for (int u : G[v]) { + if (!visited[u]) + dfs(u); + } + ans.push_back(v); +} + +void topological_sort() { + visited.assign(n, false); + ans.clear(); + for (int i = 0; i < n; ++i) { + if (!visited[i]) + dfs(i); + } + reverse(ans.begin(), ans.end()); +} +int main() { + cout << "Enter the number of vertices and the number of directed edges\n"; + cin >> n >> m; + int x, y; + G.resize(n, vector()); + for (int i = 0; i < n; ++i) { + cin >> x >> y; + x--, y--; // to convert 1-indexed to 0-indexed + G[x].push_back(y); + } + topological_sort(); + cout << "Topological Order : \n"; + for (int v : ans) { + cout << v + 1 + << ' '; // converting zero based indexing back to one based. + } + cout << '\n'; + return 0; +} diff --git a/graph/topological_sort_by_kahns_algo.cpp b/graph/topological_sort_by_kahns_algo.cpp index eda2a74bc..57ee01b23 100644 --- a/graph/topological_sort_by_kahns_algo.cpp +++ b/graph/topological_sort_by_kahns_algo.cpp @@ -1,8 +1,8 @@ #include #include #include -#include #include +#include int *topoSortKahn(int N, std::vector adj[]); @@ -13,7 +13,7 @@ int main() { return 0; int u, v; - std::vectorgraph[nodes]; + std::vector graph[nodes]; // create graph // example // 6 6 @@ -31,23 +31,23 @@ int main() { } } -int* topoSortKahn(int V, std::vector adj[]) { - std::vectorvis(V+1, false); - std::vectordeg(V+1, 0); +int *topoSortKahn(int V, std::vector adj[]) { + std::vector vis(V + 1, false); + std::vector deg(V + 1, 0); for (int i = 0; i < V; i++) { for (int j = 0; j < adj[i].size(); j++) { deg[adj[i][j]]++; } } - std::queueq; + std::queue q; for (int i = 0; i < V; i++) { if (deg[i] == 0) { q.push(i); vis[i] = true; } } - int *arr = new int[V+1]; - memset(arr, 0, V+1); + int *arr = new int[V + 1]; + memset(arr, 0, V + 1); int count = 0; while (!q.empty()) { int cur = q.front(); diff --git a/greedy_algorithms/Knapsack.cpp b/greedy_algorithms/Knapsack.cpp deleted file mode 100644 index 2135bd1eb..000000000 --- a/greedy_algorithms/Knapsack.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include -using namespace std; - -struct Item -{ - int weight; - int profit; -}; - -float profitPerUnit(Item x) -{ - return (float)x.profit / (float)x.weight; -} - -int partition(Item arr[], int low, int high) -{ - Item pivot = arr[high]; // 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 (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) - { - i++; // increment index of smaller element - Item temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } - } - Item temp = arr[i + 1]; - arr[i + 1] = arr[high]; - arr[high] = temp; - return (i + 1); -} - -void quickSort(Item arr[], int low, int high) -{ - if (low < high) - { - - int p = partition(arr, low, high); - - quickSort(arr, low, p - 1); - quickSort(arr, p + 1, high); - } -} - -int main() -{ - cout << "\nEnter the capacity of the knapsack : "; - float capacity; - cin >> capacity; - cout << "\n Enter the number of Items : "; - int n; - cin >> n; - Item itemArray[n]; - for (int i = 0; i < n; i++) - { - cout << "\nEnter the weight and profit of item " << i + 1 << " : "; - cin >> itemArray[i].weight; - cin >> itemArray[i].profit; - } - - quickSort(itemArray, 0, n - 1); - - // show(itemArray, n); - - float maxProfit = 0; - int i = n; - while (capacity > 0 && --i >= 0) - { - if (capacity >= itemArray[i].weight) - { - maxProfit += itemArray[i].profit; - capacity -= itemArray[i].weight; - cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit; - } - else - { - maxProfit += profitPerUnit(itemArray[i]) * capacity; - cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity; - capacity = 0; - break; - } - } - - cout << "\nMax Profit : " << maxProfit; - - return 0; -} diff --git a/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp b/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp deleted file mode 100644 index 951d4a88a..000000000 --- a/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -using namespace std; - -#define V 6 -#define INFINITY 99999 - -int graph[V][V] = { - {0, 4, 1, 4, INFINITY, INFINITY}, - {4, 0, 3, 8, 3, INFINITY}, - {1, 3, 0, INFINITY, 1, INFINITY}, - {4, 8, INFINITY, 0, 5, 7}, - {INFINITY, 3, 1, 5, 0, INFINITY}, - {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; - -void findMinimumEdge() -{ - for (int i = 0; i < V; i++) - { - int min = INFINITY; - int minIndex = 0; - for (int j = 0; j < V; j++) - { - if (graph[i][j] != 0 && graph[i][j] < min) - { - min = graph[i][j]; - minIndex = j; - } - } - cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n"; - } -} - -int main() -{ - findMinimumEdge(); - return 0; -} diff --git a/greedy_algorithms/Prims Minimum Spanning Tree.cpp b/greedy_algorithms/Prims Minimum Spanning Tree.cpp deleted file mode 100644 index 769ca64e4..000000000 --- a/greedy_algorithms/Prims Minimum Spanning Tree.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include -using namespace std; - -#define V 4 -#define INFINITY 99999 - -int graph[V][V] = { - {0, 5, 1, 2}, - {5, 0, 3, 3}, - {1, 3, 0, 4}, - {2, 3, 4, 0}}; - -struct mst -{ - bool visited; - int key; - int near; -}; - -mst MST_Array[V]; - -void initilize() -{ - for (int i = 0; i < V; i++) - { - MST_Array[i].visited = false; - MST_Array[i].key = INFINITY; // considering INFINITY as inifinity - MST_Array[i].near = i; - } - - MST_Array[0].key = 0; -} - -void updateNear() -{ - for (int v = 0; v < V; v++) - { - int min = INFINITY; - int minIndex = 0; - for (int i = 0; i < V; i++) - { - if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY) - { - min = MST_Array[i].key; - minIndex = i; - } - } - - MST_Array[minIndex].visited = true; - - for (int i = 0; i < V; i++) - { - if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) - { - if (graph[minIndex][i] < MST_Array[i].key) - { - MST_Array[i].key = graph[minIndex][i]; - MST_Array[i].near = minIndex; - } - } - } - } -} - -void show() -{ - for (int i = 0; i < V; i++) - { - cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n"; - } -} - -int main() -{ - initilize(); - updateNear(); - show(); - return 0; -} diff --git a/greedy_algorithms/Dijkstra.cpp b/greedy_algorithms/dijkstra.cpp similarity index 53% rename from greedy_algorithms/Dijkstra.cpp rename to greedy_algorithms/dijkstra.cpp index 0c7fffc8c..e4450379c 100644 --- a/greedy_algorithms/Dijkstra.cpp +++ b/greedy_algorithms/dijkstra.cpp @@ -1,31 +1,25 @@ -#include #include +#include using namespace std; -//Wrapper class for storing a graph -class Graph -{ -public: +// Wrapper class for storing a graph +class Graph { + public: int vertexNum; int **edges; - //Constructs a graph with V vertices and E edges - Graph(const int V) - { - + // Constructs a graph with V vertices and E edges + Graph(const int V) { // initializes the array edges. this->edges = new int *[V]; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { edges[i] = new int[V]; } // fills the array with zeros. - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { edges[i][j] = 0; } } @@ -33,20 +27,16 @@ public: this->vertexNum = V; } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) { this->edges[src][dst] = weight; } }; -//Utility function to find minimum distance vertex in mdist -int minDistance(int mdist[], bool vset[], int V) -{ +// Utility function to find minimum distance vertex in mdist +int minDistance(int mdist[], bool vset[], int V) { int minVal = INT_MAX, minInd = 0; - for (int i = 0; i < V; i++) - { - if (!vset[i] && (mdist[i] < minVal)) - { + for (int i = 0; i < V; i++) { + if (!vset[i] && (mdist[i] < minVal)) { minVal = mdist[i]; minInd = i; } @@ -55,12 +45,10 @@ int minDistance(int mdist[], bool vset[], int V) return minInd; } -//Utility function to print distances -void print(int dist[], int V) -{ +// Utility function to print distances +void print(int dist[], int V) { cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { if (dist[i] < INT_MAX) cout << i << "\t" << dist[i] << endl; else @@ -68,36 +56,32 @@ void print(int dist[], int V) } } -//The main function that finds the shortest path from given source -//to all other vertices using Dijkstra's Algorithm.It doesn't work on negative -//weights -void Dijkstra(Graph graph, int src) -{ +// The main function that finds the shortest path from given source +// to all other vertices using Dijkstra's Algorithm.It doesn't work on negative +// weights +void Dijkstra(Graph graph, int src) { int V = graph.vertexNum; - int mdist[V]; //Stores updated distances to vertex - bool vset[V]; // vset[i] is true if the vertex i included + int mdist[V]; // Stores updated distances to vertex + bool vset[V]; // vset[i] is true if the vertex i included // in the shortest path tree - //Initialise mdist and vset. Set distance of source as zero - for (int i = 0; i < V; i++) - { + // Initialise mdist and vset. Set distance of source as zero + for (int i = 0; i < V; i++) { mdist[i] = INT_MAX; vset[i] = false; } mdist[src] = 0; - //iterate to find shortest path - for (int count = 0; count < V - 1; count++) - { + // iterate to find shortest path + for (int count = 0; count < V - 1; count++) { int u = minDistance(mdist, vset, V); vset[u] = true; - for (int v = 0; v < V; v++) - { - if (!vset[v] && graph.edges[u][v] && mdist[u] + graph.edges[u][v] < mdist[v]) - { + for (int v = 0; v < V; v++) { + if (!vset[v] && graph.edges[u][v] && + mdist[u] + graph.edges[u][v] < mdist[v]) { mdist[v] = mdist[u] + graph.edges[u][v]; } } @@ -106,9 +90,8 @@ void Dijkstra(Graph graph, int src) print(mdist, V); } -//Driver Function -int main() -{ +// Driver Function +int main() { int V, E, gsrc; int src, dst, weight; cout << "Enter number of vertices: "; @@ -116,8 +99,7 @@ int main() cout << "Enter number of edges: "; cin >> E; Graph G(V); - for (int i = 0; i < E; i++) - { + for (int i = 0; i < E; i++) { cout << "\nEdge " << i + 1 << "\nEnter source: "; cin >> src; cout << "Enter destination: "; @@ -126,12 +108,9 @@ int main() cin >> weight; // makes sure source and destionation are in the proper bounds. - if (src >= 0 && src < V && dst >= 0 && dst < V) - { + if (src >= 0 && src < V && dst >= 0 && dst < V) { G.addEdge(src, dst, weight); - } - else - { + } else { cout << "source and/or destination out of bounds" << endl; i--; continue; diff --git a/greedy_algorithms/huffman.cpp b/greedy_algorithms/huffman.cpp index 253d8d0b5..21c8295f3 100644 --- a/greedy_algorithms/huffman.cpp +++ b/greedy_algorithms/huffman.cpp @@ -1,109 +1,100 @@ -// C++ program for Huffman Coding +// C++ program for Huffman Coding #include -#include -using namespace std; - -// A Huffman tree node -struct MinHeapNode { - - // One of the input characters - char data; - - // Frequency of the character - unsigned freq; - - // Left and right child - MinHeapNode *left, *right; - - MinHeapNode(char data, unsigned freq) - - { - - left = right = NULL; - this->data = data; - this->freq = freq; - } -}; - -// For comparison of -// two heap nodes (needed in min heap) -struct compare { - - bool operator()(MinHeapNode* l, MinHeapNode* r) - - { - return (l->freq > r->freq); - } -}; - -// Prints huffman codes from -// the root of Huffman Tree. -void printCodes(struct MinHeapNode* root, string str) -{ - - if (!root) - return; - - if (root->data != '$') - cout << root->data << ": " << str << "\n"; - - printCodes(root->left, str + "0"); - printCodes(root->right, str + "1"); -} - -// The main function that builds a Huffman Tree and -// print codes by traversing the built Huffman Tree -void HuffmanCodes(char data[], int freq[], int size) -{ - struct MinHeapNode *left, *right, *top; - - // Create a min heap & inserts all characters of data[] - priority_queue, compare> minHeap; - - for (int i = 0; i < size; ++i) - minHeap.push(new MinHeapNode(data[i], freq[i])); - - // Iterate while size of heap doesn't become 1 - while (minHeap.size() != 1) { - - // Extract the two minimum - // freq items from min heap - left = minHeap.top(); - minHeap.pop(); - - right = minHeap.top(); - minHeap.pop(); - - // Create a new internal node with - // frequency equal to the sum of the - // two nodes frequencies. Make the - // two extracted node as left and right children - // of this new node. Add this node - // to the min heap '$' is a special value - // for internal nodes, not used - top = new MinHeapNode('$', left->freq + right->freq); - - top->left = left; - top->right = right; - - minHeap.push(top); - } - - // Print Huffman codes using - // the Huffman tree built above - printCodes(minHeap.top(), ""); -} - -// Driver program to test above functions -int main() -{ - - char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; - int freq[] = { 5, 9, 12, 13, 16, 45 }; - - int size = sizeof(arr) / sizeof(arr[0]); - - HuffmanCodes(arr, freq, size); - - return 0; -} +#include +using namespace std; + +// A Huffman tree node +struct MinHeapNode { + // One of the input characters + char data; + + // Frequency of the character + unsigned freq; + + // Left and right child + MinHeapNode *left, *right; + + MinHeapNode(char data, unsigned freq) + + { + left = right = NULL; + this->data = data; + this->freq = freq; + } +}; + +// For comparison of +// two heap nodes (needed in min heap) +struct compare { + bool operator()(MinHeapNode* l, MinHeapNode* r) + + { + return (l->freq > r->freq); + } +}; + +// Prints huffman codes from +// the root of Huffman Tree. +void printCodes(struct MinHeapNode* root, string str) { + if (!root) + return; + + if (root->data != '$') + cout << root->data << ": " << str << "\n"; + + printCodes(root->left, str + "0"); + printCodes(root->right, str + "1"); +} + +// The main function that builds a Huffman Tree and +// print codes by traversing the built Huffman Tree +void HuffmanCodes(char data[], int freq[], int size) { + struct MinHeapNode *left, *right, *top; + + // Create a min heap & inserts all characters of data[] + priority_queue, compare> minHeap; + + for (int i = 0; i < size; ++i) + minHeap.push(new MinHeapNode(data[i], freq[i])); + + // Iterate while size of heap doesn't become 1 + while (minHeap.size() != 1) { + // Extract the two minimum + // freq items from min heap + left = minHeap.top(); + minHeap.pop(); + + right = minHeap.top(); + minHeap.pop(); + + // Create a new internal node with + // frequency equal to the sum of the + // two nodes frequencies. Make the + // two extracted node as left and right children + // of this new node. Add this node + // to the min heap '$' is a special value + // for internal nodes, not used + top = new MinHeapNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + minHeap.push(top); + } + + // Print Huffman codes using + // the Huffman tree built above + printCodes(minHeap.top(), ""); +} + +// Driver program to test above functions +int main() { + char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; + int freq[] = {5, 9, 12, 13, 16, 45}; + + int size = sizeof(arr) / sizeof(arr[0]); + + HuffmanCodes(arr, freq, size); + + return 0; +} diff --git a/greedy_algorithms/knapsack.cpp b/greedy_algorithms/knapsack.cpp new file mode 100644 index 000000000..74be4fee0 --- /dev/null +++ b/greedy_algorithms/knapsack.cpp @@ -0,0 +1,78 @@ +#include +using namespace std; + +struct Item { + int weight; + int profit; +}; + +float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; } + +int partition(Item arr[], int low, int high) { + Item pivot = arr[high]; // 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 (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) { + i++; // increment index of smaller element + Item temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + Item temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return (i + 1); +} + +void quickSort(Item arr[], int low, int high) { + if (low < high) { + int p = partition(arr, low, high); + + quickSort(arr, low, p - 1); + quickSort(arr, p + 1, high); + } +} + +int main() { + cout << "\nEnter the capacity of the knapsack : "; + float capacity; + cin >> capacity; + cout << "\n Enter the number of Items : "; + int n; + cin >> n; + Item itemArray[n]; + for (int i = 0; i < n; i++) { + cout << "\nEnter the weight and profit of item " << i + 1 << " : "; + cin >> itemArray[i].weight; + cin >> itemArray[i].profit; + } + + quickSort(itemArray, 0, n - 1); + + // show(itemArray, n); + + float maxProfit = 0; + int i = n; + while (capacity > 0 && --i >= 0) { + if (capacity >= itemArray[i].weight) { + maxProfit += itemArray[i].profit; + capacity -= itemArray[i].weight; + cout << "\n\t" << itemArray[i].weight << "\t" + << itemArray[i].profit; + } else { + maxProfit += profitPerUnit(itemArray[i]) * capacity; + cout << "\n\t" << capacity << "\t" + << profitPerUnit(itemArray[i]) * capacity; + capacity = 0; + break; + } + } + + cout << "\nMax Profit : " << maxProfit; + + return 0; +} diff --git a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp new file mode 100644 index 000000000..9f35e86ac --- /dev/null +++ b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +#define V 6 +#define INFINITY 99999 + +int graph[V][V] = {{0, 4, 1, 4, INFINITY, INFINITY}, + {4, 0, 3, 8, 3, INFINITY}, + {1, 3, 0, INFINITY, 1, INFINITY}, + {4, 8, INFINITY, 0, 5, 7}, + {INFINITY, 3, 1, 5, 0, INFINITY}, + {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; + +void findMinimumEdge() { + for (int i = 0; i < V; i++) { + int min = INFINITY; + int minIndex = 0; + for (int j = 0; j < V; j++) { + if (graph[i][j] != 0 && graph[i][j] < min) { + min = graph[i][j]; + minIndex = j; + } + } + cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n"; + } +} + +int main() { + findMinimumEdge(); + return 0; +} diff --git a/greedy_algorithms/prims_minimum_spanning_tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp new file mode 100644 index 000000000..c804c176d --- /dev/null +++ b/greedy_algorithms/prims_minimum_spanning_tree.cpp @@ -0,0 +1,64 @@ +#include +using namespace std; + +#define V 4 +#define INFINITY 99999 + +int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}}; + +struct mst { + bool visited; + int key; + int near; +}; + +mst MST_Array[V]; + +void initilize() { + for (int i = 0; i < V; i++) { + MST_Array[i].visited = false; + MST_Array[i].key = INFINITY; // considering INFINITY as inifinity + MST_Array[i].near = i; + } + + MST_Array[0].key = 0; +} + +void updateNear() { + for (int v = 0; v < V; v++) { + int min = INFINITY; + int minIndex = 0; + for (int i = 0; i < V; i++) { + if (MST_Array[i].key < min && MST_Array[i].visited == false && + MST_Array[i].key != INFINITY) { + min = MST_Array[i].key; + minIndex = i; + } + } + + MST_Array[minIndex].visited = true; + + for (int i = 0; i < V; i++) { + if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) { + if (graph[minIndex][i] < MST_Array[i].key) { + MST_Array[i].key = graph[minIndex][i]; + MST_Array[i].near = minIndex; + } + } + } + } +} + +void show() { + for (int i = 0; i < V; i++) { + cout << i << " - " << MST_Array[i].near << "\t" + << graph[i][MST_Array[i].near] << "\n"; + } +} + +int main() { + initilize(); + updateNear(); + show(); + return 0; +} diff --git a/hashing/Chaining.cpp b/hashing/Chaining.cpp deleted file mode 100644 index 55aa8961c..000000000 --- a/hashing/Chaining.cpp +++ /dev/null @@ -1,140 +0,0 @@ -#include -#include -using namespace std; - -struct Node -{ - int data; - struct Node *next; -} * head[100], *curr; - -void init() -{ - for (int i = 0; i < 100; i++) - head[i] = NULL; -} - -void add(int x, int h) -{ - struct Node *temp = new Node; - temp->data = x; - temp->next = NULL; - if (!head[h]) - { - head[h] = temp; - curr = head[h]; - } - else - { - curr = head[h]; - while (curr->next) - curr = curr->next; - curr->next = temp; - } -} - -void display(int mod) -{ - struct Node *temp; - int i; - for (i = 0; i < mod; i++) - { - if (!head[i]) - { - cout << "Key " << i << " is empty" << endl; - } - else - { - cout << "Key " << i << " has values = "; - temp = head[i]; - while (temp->next) - { - cout << temp->data << " "; - temp = temp->next; - } - cout << temp->data; - cout << endl; - } - } -} - -int hash(int x, int mod) -{ - return x % mod; -} - -void find(int x, int h) -{ - struct Node *temp = head[h]; - if (!head[h]) - { - cout << "Element not found"; - return; - } - while (temp->data != x && temp->next) - temp = temp->next; - if (temp->next) - cout << "Element found"; - else - { - if (temp->data == x) - cout << "Element found"; - else - cout << "Element not found"; - } -} - -int main(void) -{ - init(); - int c, x, mod, h; - cout << "Enter the size of Hash Table. = "; - cin >> mod; - bool loop = true; - while (loop) - { - cout << endl; - cout << "PLEASE CHOOSE -" << endl; - cout << "1. Add element." << endl; - cout << "2. Find element." << endl; - cout << "3. Generate Hash." << endl; - cout << "4. Display Hash table." << endl; - cout << "5. Exit." << endl; - cin >> c; - switch (c) - { - case 1: - cout << "Enter element to add = "; - cin >> x; - h = hash(x, mod); - h = fabs(h); - add(x, h); - break; - case 2: - cout << "Enter element to search = "; - cin >> x; - h = hash(x, mod); - find(x, h); - break; - case 3: - cout << "Enter element to generate hash = "; - cin >> x; - cout << "Hash of " << x << " is = " << hash(x, mod); - break; - case 4: - display(mod); - break; - default: - loop = false; - break; - } - cout << endl; - } - /*add(1,&head1); - add(2,&head1); - add(3,&head2); - add(5,&head1); - display(&head1); - display(&head2);*/ - return 0; -} \ No newline at end of file diff --git a/hashing/chaining.cpp b/hashing/chaining.cpp new file mode 100644 index 000000000..6afd2d13b --- /dev/null +++ b/hashing/chaining.cpp @@ -0,0 +1,116 @@ +#include +#include +using namespace std; + +struct Node { + int data; + struct Node *next; +} * head[100], *curr; + +void init() { + for (int i = 0; i < 100; i++) head[i] = NULL; +} + +void add(int x, int h) { + struct Node *temp = new Node; + temp->data = x; + temp->next = NULL; + if (!head[h]) { + head[h] = temp; + curr = head[h]; + } else { + curr = head[h]; + while (curr->next) curr = curr->next; + curr->next = temp; + } +} + +void display(int mod) { + struct Node *temp; + int i; + for (i = 0; i < mod; i++) { + if (!head[i]) { + cout << "Key " << i << " is empty" << endl; + } else { + cout << "Key " << i << " has values = "; + temp = head[i]; + while (temp->next) { + cout << temp->data << " "; + temp = temp->next; + } + cout << temp->data; + cout << endl; + } + } +} + +int hash(int x, int mod) { return x % mod; } + +void find(int x, int h) { + struct Node *temp = head[h]; + if (!head[h]) { + cout << "Element not found"; + return; + } + while (temp->data != x && temp->next) temp = temp->next; + if (temp->next) + cout << "Element found"; + else { + if (temp->data == x) + cout << "Element found"; + else + cout << "Element not found"; + } +} + +int main(void) { + init(); + int c, x, mod, h; + cout << "Enter the size of Hash Table. = "; + cin >> mod; + bool loop = true; + while (loop) { + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add element." << endl; + cout << "2. Find element." << endl; + cout << "3. Generate Hash." << endl; + cout << "4. Display Hash table." << endl; + cout << "5. Exit." << endl; + cin >> c; + switch (c) { + case 1: + cout << "Enter element to add = "; + cin >> x; + h = hash(x, mod); + h = fabs(h); + add(x, h); + break; + case 2: + cout << "Enter element to search = "; + cin >> x; + h = hash(x, mod); + find(x, h); + break; + case 3: + cout << "Enter element to generate hash = "; + cin >> x; + cout << "Hash of " << x << " is = " << hash(x, mod); + break; + case 4: + display(mod); + break; + default: + loop = false; + break; + } + cout << endl; + } + /*add(1,&head1); + add(2,&head1); + add(3,&head2); + add(5,&head1); + display(&head1); + display(&head2);*/ + return 0; +} \ No newline at end of file diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp index 6030b7ff3..7ee2757de 100644 --- a/hashing/double_hash_hash_table.cpp +++ b/hashing/double_hash_hash_table.cpp @@ -1,13 +1,13 @@ // Copyright 2019 -#include -#include -#include -#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -48,8 +48,8 @@ int doubleHash(int key, bool searching) { int i = 0; Entry entry; do { - int index = static_cast(fabs((hash + - (i * otherHashFxn(key))))) % totalSize; + int index = static_cast(fabs((hash + (i * otherHashFxn(key))))) % + totalSize; entry = table[index]; if (searching) { if (entry.key == notPresent) { @@ -63,12 +63,17 @@ int doubleHash(int key, bool searching) { i++; } else { if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) cout << "Spot taken, looking at next (next index:" - << " " << static_cast(fabs((hash + - (i * otherHashFxn(key))))) % totalSize << ")" << endl; + if (!rehashing) + cout << "Spot taken, looking at next (next index:" + << " " + << static_cast( + fabs((hash + (i * otherHashFxn(key))))) % + totalSize + << ")" << endl; i++; } if (i == totalSize * 100) { @@ -89,7 +94,8 @@ bool putProber(Entry entry, int key) { // Looks for a matching key bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; + if (entry.key == key) + return true; return false; } @@ -131,12 +137,12 @@ void rehash() { // Checks for load factor here void add(int key) { - Entry * entry = new Entry(); + Entry* entry = new Entry(); entry->key = key; int index = doubleHash(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } @@ -157,8 +163,8 @@ void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -170,8 +176,8 @@ void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp index b00eb8641..393504c1d 100644 --- a/hashing/linear_probing_hash_table.cpp +++ b/hashing/linear_probing_hash_table.cpp @@ -1,13 +1,13 @@ // Copyright 2019 -#include -#include -#include -#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -56,10 +56,12 @@ int linearProbe(int key, bool searching) { i++; } else { if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) cout << "Spot taken, looking at next" << endl; + if (!rehashing) + cout << "Spot taken, looking at next" << endl; i++; } if (i == totalSize) { @@ -80,7 +82,8 @@ bool putProber(Entry entry, int key) { // Looks for a matching key bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; + if (entry.key == key) + return true; return false; } @@ -122,12 +125,12 @@ void rehash() { // Adds entry using linear probing. Checks for load factor here void add(int key) { - Entry * entry = new Entry(); + Entry* entry = new Entry(); entry->key = key; int index = linearProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } @@ -148,8 +151,8 @@ void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) << " % " - << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -161,8 +164,8 @@ void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp index 44e2e3b9f..971c2182d 100644 --- a/hashing/quadratic_probing_hash_table.cpp +++ b/hashing/quadratic_probing_hash_table.cpp @@ -1,14 +1,14 @@ // Copyright 2019 -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -43,8 +43,8 @@ int quadraticProbe(int key, bool searching) { int i = 0; Entry entry; do { - int index = std::round(fabs((hash + - static_cast(std::round(std::pow(i, 2)))) % totalSize)); + int index = std::round(fabs( + (hash + static_cast(std::round(std::pow(i, 2)))) % totalSize)); entry = table[index]; if (searching) { if (entry.key == notPresent) { @@ -58,13 +58,16 @@ int quadraticProbe(int key, bool searching) { i++; } else { if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + if (!rehashing) + cout << "Spot found!" << endl; return index; } if (!rehashing) { - cout << "Spot taken, looking at next (next index = " << - std::round(fabs((hash + static_cast(std::round( - std::pow(i + 1, 2)))) % totalSize)) << endl; + cout << "Spot taken, looking at next (next index = " + << std::round(fabs((hash + static_cast(std::round( + std::pow(i + 1, 2)))) % + totalSize)) + << endl; } i++; } @@ -86,14 +89,16 @@ bool putProber(Entry entry, int key) { // Looks for a matching key bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; + if (entry.key == key) + return true; return false; } // Helper Entry find(int key) { int index = quadraticProbe(key, true); - if (index == notPresent) return Entry(); + if (index == notPresent) + return Entry(); return table[index]; } @@ -135,12 +140,12 @@ void rehash() { // Checks for load factor here void add(int key) { - Entry * entry = new Entry(); + Entry* entry = new Entry(); entry->key = key; int index = quadraticProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } @@ -161,8 +166,8 @@ void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) << " % " - << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -174,8 +179,8 @@ void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 37bd2052a..8e5ffcefa 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -16,7 +16,8 @@ uint64_t double_factorial_iterative(uint64_t n) { uint64_t res = 1; for (uint64_t i = n;; i -= 2) { - if (i == 0 || i == 1) return res; + if (i == 0 || i == 1) + return res; res *= i; } return res; @@ -26,7 +27,8 @@ uint64_t double_factorial_iterative(uint64_t n) { *
Recursion can be costly for large numbers. */ uint64_t double_factorial_recursive(uint64_t n) { - if (n <= 1) return 1; + if (n <= 1) + return 1; return n * double_factorial_recursive(n - 2); } diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index e7f6fbf7f..8283ab045 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -39,7 +39,8 @@ uint64_t phiFunction(uint64_t n) { result -= result / i; } } - if (n > 1) result -= result / n; + if (n > 1) + result -= result / n; return result; } diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 3fdae25b5..9fdc9692e 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -39,7 +39,8 @@ inline void update_step(T *r, T *r0, const T2 quotient) { */ template void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { - if (B > A) std::swap(A, B); // Ensure that A >= B + if (B > A) + std::swap(A, B); // Ensure that A >= B T2 s = 0, s0 = 1; T2 t = 1, t0 = 0; @@ -67,7 +68,8 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { */ template void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { - if (B > A) std::swap(A, B); // Ensure that A >= B + if (B > A) + std::swap(A, B); // Ensure that A >= B if (B == 0) { *GCD = A; diff --git a/math/fast_power.cpp b/math/fast_power.cpp index d4de07460..c5621cd4e 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -25,9 +25,11 @@ template double fast_power_recursive(T a, T b) { // negative power. a^b = 1 / (a^-b) - if (b < 0) return 1.0 / fast_power_recursive(a, -b); + if (b < 0) + return 1.0 / fast_power_recursive(a, -b); - if (b == 0) return 1; + if (b == 0) + return 1; T bottom = fast_power_recursive(a, b >> 1); // Since it is integer division b/2 = (b-1)/2 where b is odd. // Therefore, case2 is easily solved by integer division. @@ -47,11 +49,13 @@ double fast_power_recursive(T a, T b) { template double fast_power_linear(T a, T b) { // negative power. a^b = 1 / (a^-b) - if (b < 0) return 1.0 / fast_power_linear(a, -b); + if (b < 0) + return 1.0 / fast_power_linear(a, -b); double result = 1; while (b) { - if (b & 1) result = result * a; + if (b & 1) + result = result * a; a = a * a; b = b >> 1; } diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index d0e05cb4c..001c2c3c3 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -31,7 +31,8 @@ void SieveOfEratosthenes(int N) { } for (int i = 2; i <= N; i++) { - if (isprime[i]) prime_numbers.push_back(i); + if (isprime[i]) + prime_numbers.push_back(i); } } @@ -52,7 +53,8 @@ void prime_factorization(int num) { number = number / prime_numbers[i]; } - if (count) factors.push_back(std::make_pair(prime_numbers[i], count)); + if (count) + factors.push_back(std::make_pair(prime_numbers[i], count)); } } diff --git a/operations_on_datastructures/Array Left Rotation.cpp b/operations_on_datastructures/Array Left Rotation.cpp deleted file mode 100644 index 9eb5d4e50..000000000 --- a/operations_on_datastructures/Array Left Rotation.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include -using namespace std; -int main() -{ - int n, k; - cout << "Enter size of array=\t"; - cin >> n; - cout << "Enter Number of indeces u want to rotate the array to left=\t"; - cin >> k; - int a[n]; - cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - { - cin >> a[i]; - } - int temp = 0; - for (int i = 0; i < k; i++) - { - temp = a[0]; - for (int j = 0; j < n; j++) - { - if (j == n - 1) - { - a[n - 1] = temp; - } - else - { - a[j] = a[j + 1]; - } - } - } - cout << "Your rotated array is=\t"; - for (int j = 0; j < n; j++) - { - cout << a[j] << " "; - } - getchar(); - return 0; -} diff --git a/operations_on_datastructures/Circular Linked List.cpp b/operations_on_datastructures/Circular Linked List.cpp deleted file mode 100644 index d360f6cd7..000000000 --- a/operations_on_datastructures/Circular Linked List.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - -node *start; - -void insert(int x) -{ - node *t = start; - - if (start != NULL) - { - while (t->next != start) - { - t = t->next; - } - node *n = new node; - t->next = n; - n->val = x; - n->next = start; - } - else - { - node *n = new node; - n->val = x; - start = n; - n->next = start; - } -} - -void remove(int x) -{ - node *t = start; - node *p; - while (t->val != x) - { - p = t; - t = t->next; - } - p->next = t->next; - delete t; -} - -void search(int x) -{ - node *t = start; - int found = 0; - while (t->next != start) - { - if (t->val == x) - { - cout << "\nFound"; - found = 1; - break; - } - t = t->next; - } - if (found == 0) - { - cout << "\nNot Found"; - } -} - -void show() -{ - node *t = start; - do - { - cout << t->val << "\t"; - t = t->next; - } while (t != start); -} - -int main() -{ - int choice, x; - do - { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Search"; - cout << "\n4. Print"; - cout << "\n\nEnter you choice : "; - cin >> choice; - switch (choice) - { - case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; - insert(x); - break; - case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; - remove(x); - break; - case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; - search(x); - break; - case 4: - show(); - break; - } - } while (choice != 0); - - return 0; -} diff --git a/operations_on_datastructures/Circular Queue Using Array.cpp b/operations_on_datastructures/Circular Queue Using Array.cpp deleted file mode 100644 index 36d7e22c3..000000000 --- a/operations_on_datastructures/Circular Queue Using Array.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include -using namespace std; - -int queue[10]; -int front = 0; -int rear = 0; -int count = 0; - -void Enque(int x) -{ - if (count == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear] = x; - rear = (rear + 1) % 10; - count++; - } -} - -void Deque() -{ - if (front == rear) - { - cout << "\nUnderflow"; - } - - else - { - cout << "\n" - << queue[front] << " deleted"; - front = (front + 1) % 10; - count--; - } -} - -void show() -{ - for (int i = 0; i < count; i++) - { - cout << queue[(i + front) % 10] << "\t"; - } -} - -int main() -{ - int ch, x; - do - { - cout << "\n1. Enque"; - cout << "\n2. Deque"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - Enque(x); - } - else if (ch == 2) - { - Deque(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); - - return 0; -} diff --git a/operations_on_datastructures/Intersection_of_2_arrays.cpp b/operations_on_datastructures/Intersection_of_2_arrays.cpp deleted file mode 100644 index 05652811f..000000000 --- a/operations_on_datastructures/Intersection_of_2_arrays.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include -int main() -{ - int i, j, m, n; - cout << "Enter size of array 1:"; - cin >> m; - cout << "Enter size of array 2:"; - cin >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for (i = 0; i < m; i++) - cin >> a[i]; - for (i = 0; i < n; i++) - cin >> b[i]; - i = 0; - j = 0; - while ((i < m) && (j < n)) - { - if (a[i] < b[j]) - i++; - else if (a[i] > b[j]) - j++; - else - { - cout << a[i++] << " "; - j++; - } - } - return 0; -} diff --git a/operations_on_datastructures/Reverse a Linked List using Recusion.cpp b/operations_on_datastructures/Reverse a Linked List using Recusion.cpp deleted file mode 100644 index 0908080cc..000000000 --- a/operations_on_datastructures/Reverse a Linked List using Recusion.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - -node *start; - -void insert(int x) -{ - node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { - t = t->next; - } - node *n = new node; - t->next = n; - n->val = x; - n->next = NULL; - } - else - { - node *n = new node; - n->val = x; - n->next = NULL; - start = n; - } -} - -void reverse(node *p, node *q) -{ - if (q->next == NULL) - { - q->next = p; - p->next = NULL; - start = q; - return; - } - else - { - reverse(q, q->next); - q->next = p; - p->next = NULL; - } -} - -void show() -{ - node *t = start; - while (t != NULL) - { - cout << t->val << "\t"; - t = t->next; - } -} - -int main() -{ - insert(1); - insert(2); - insert(3); - insert(4); - insert(5); - insert(6); - - reverse(start, start->next); - - show(); - - return 0; -} diff --git a/operations_on_datastructures/Union_of_2_arrays.cpp b/operations_on_datastructures/Union_of_2_arrays.cpp deleted file mode 100644 index aaaeb8378..000000000 --- a/operations_on_datastructures/Union_of_2_arrays.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -int main() -{ - int m, n, i = 0, j = 0; - cout << "Enter size of both arrays:"; - cin >> m >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for (i = 0; i < m; i++) - cin >> a[i]; - cout << "Enter elements of array 2:"; - for (i = 0; i < n; i++) - cin >> b[i]; - i = 0; - j = 0; - while ((i < m) && (j < n)) - { - if (a[i] < b[j]) - cout << a[i++] << " "; - else if (a[i] > b[j]) - cout << b[j++] << " "; - else - { - cout << a[i++]; - j++; - } - } - while (i < m) - cout << a[i++] << " "; - while (j < n) - cout << b[j++] << " "; - return 0; -} diff --git a/operations_on_datastructures/array_left_rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp new file mode 100644 index 000000000..7b8f7f279 --- /dev/null +++ b/operations_on_datastructures/array_left_rotation.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; +int main() { + int n, k; + cout << "Enter size of array=\t"; + cin >> n; + cout << "Enter Number of indeces u want to rotate the array to left=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) { + cin >> a[i]; + } + int temp = 0; + for (int i = 0; i < k; i++) { + temp = a[0]; + for (int j = 0; j < n; j++) { + if (j == n - 1) { + a[n - 1] = temp; + } else { + a[j] = a[j + 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int j = 0; j < n; j++) { + cout << a[j] << " "; + } + getchar(); + return 0; +} diff --git a/operations_on_datastructures/Array Right Rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp similarity index 62% rename from operations_on_datastructures/Array Right Rotation.cpp rename to operations_on_datastructures/array_right_rotation.cpp index 81875766c..8b01a2003 100644 --- a/operations_on_datastructures/Array Right Rotation.cpp +++ b/operations_on_datastructures/array_right_rotation.cpp @@ -1,7 +1,6 @@ #include using namespace std; -int main() -{ +int main() { int n, k; cout << "Enter size of array=\t"; cin >> n; @@ -9,27 +8,20 @@ int main() cin >> k; int a[n]; cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - cin >> a[i]; + for (int i = 0; i < n; i++) cin >> a[i]; int temp = 0; - for (int i = 0; i < k; i++) - { + for (int i = 0; i < k; i++) { temp = a[n - 1]; - for (int j = n - 1; j >= 0; j--) - { - if (j == 0) - { + for (int j = n - 1; j >= 0; j--) { + if (j == 0) { a[j] = temp; - } - else - { + } else { a[j] = a[j - 1]; } } } cout << "Your rotated array is=\t"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { cout << a[i] << " "; } } diff --git a/operations_on_datastructures/circular_linked_list.cpp b/operations_on_datastructures/circular_linked_list.cpp new file mode 100644 index 000000000..1119bb5e7 --- /dev/null +++ b/operations_on_datastructures/circular_linked_list.cpp @@ -0,0 +1,97 @@ +#include +using namespace std; + +struct node { + int val; + node *next; +}; + +node *start; + +void insert(int x) { + node *t = start; + + if (start != NULL) { + while (t->next != start) { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = start; + } else { + node *n = new node; + n->val = x; + start = n; + n->next = start; + } +} + +void remove(int x) { + node *t = start; + node *p; + while (t->val != x) { + p = t; + t = t->next; + } + p->next = t->next; + delete t; +} + +void search(int x) { + node *t = start; + int found = 0; + while (t->next != start) { + if (t->val == x) { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + cout << "\nNot Found"; + } +} + +void show() { + node *t = start; + do { + cout << t->val << "\t"; + t = t->next; + } while (t != start); +} + +int main() { + int choice, x; + do { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + cout << "\n\nEnter you choice : "; + cin >> choice; + switch (choice) { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + break; + } + } while (choice != 0); + + return 0; +} diff --git a/operations_on_datastructures/circular_queue_using_array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp new file mode 100644 index 000000000..e0e049611 --- /dev/null +++ b/operations_on_datastructures/circular_queue_using_array.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +int queue[10]; +int front = 0; +int rear = 0; +int count = 0; + +void Enque(int x) { + if (count == 10) { + cout << "\nOverflow"; + } else { + queue[rear] = x; + rear = (rear + 1) % 10; + count++; + } +} + +void Deque() { + if (front == rear) { + cout << "\nUnderflow"; + } + + else { + cout << "\n" << queue[front] << " deleted"; + front = (front + 1) % 10; + count--; + } +} + +void show() { + for (int i = 0; i < count; i++) { + cout << queue[(i + front) % 10] << "\t"; + } +} + +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; +} diff --git a/operations_on_datastructures/intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp new file mode 100644 index 000000000..8a3b27edf --- /dev/null +++ b/operations_on_datastructures/intersection_of_2_arrays.cpp @@ -0,0 +1,26 @@ +#include +int main() { + int i, j, m, n; + cout << "Enter size of array 1:"; + cin >> m; + cout << "Enter size of array 2:"; + cin >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) cin >> a[i]; + for (i = 0; i < n; i++) cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; + else { + cout << a[i++] << " "; + j++; + } + } + return 0; +} diff --git a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp new file mode 100644 index 000000000..b9540d951 --- /dev/null +++ b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; + +struct node { + int val; + node *next; +}; + +node *start; + +void insert(int x) { + node *t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = NULL; + } else { + node *n = new node; + n->val = x; + n->next = NULL; + start = n; + } +} + +void reverse(node *p, node *q) { + if (q->next == NULL) { + q->next = p; + p->next = NULL; + start = q; + return; + } else { + reverse(q, q->next); + q->next = p; + p->next = NULL; + } +} + +void show() { + node *t = start; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } +} + +int main() { + insert(1); + insert(2); + insert(3); + insert(4); + insert(5); + insert(6); + + reverse(start, start->next); + + show(); + + return 0; +} diff --git a/operations_on_datastructures/selectionSortLinkedList.cpp b/operations_on_datastructures/selectionSortLinkedList.cpp deleted file mode 100644 index 52363ceff..000000000 --- a/operations_on_datastructures/selectionSortLinkedList.cpp +++ /dev/null @@ -1,159 +0,0 @@ -#include -using namespace std; - -//node defined -class node -{ -public: - int data; - node *link; - node(int d) - { - data = d; - link = NULL; - } -}; - -//printing the linked list -void print(node *head) -{ - node *current = head; - while (current != NULL) - { - cout << current->data << " "; - current = current->link; - } - cout << endl; -} - -//creating the linked list with 'n' nodes -node *createlist(int n) -{ - node *head = NULL; - node *t = NULL; - for (int i = 0; i < n; i++) - { - node *temp = NULL; - int num; - cin >> num; - temp = new node(num); - if (head == NULL) - { - head = temp; - t = temp; - continue; - } - if (t->link == NULL) - t->link = temp; - t = temp; - } - return head; -} - -//performing selection sort on the linked list in an iterative manner -void my_selection_sort_linked_list(node *&head) -{ - node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning - //while scanning if we find a node 'X' with value lesser than min, - //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' - node *current = min->link; // 'current' refers to the current node we are scanning - node *previous = min; //'previous' refers to the node that is previous to the current node - node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. - //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL - //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' - //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. - //Eg. Let suppose initially we have 5->4->1->3->2->NULL - //After 1st iteration : 1->4->5->3->2->NULL and so on - - while (min->link != NULL) //so that all the nodes are scanned or until there exists a node - { - //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node - - while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X - { - if (current->data < min->data) //if the current node is smaller than the presumed node 'min' - { - if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time - { - if (previous == min) //if the 'previous' is pointing to the 'min' node - { - //Update the pointers - head = current; //update the head pointer with the current node - min->link = current->link; - current->link = previous; - min = current; - current = previous->link; - } - else //if the 'previous' is not pointing to the 'min' node - { - //Update the pointers - head = current; //update the head pointer with the current node - previous->link = current->link; - current->link = min; - min = current; - current = previous->link; - } - } - else //if 'temp' is not NULL, i.e., its not the 1st iteration - { - temp->link = current; - previous->link = current->link; - current->link = min; - min = current; - current = previous->link; - } - } - else //if the current node is greater than min, just move the previous and the current pointer a step further - { - previous = previous->link; - current = current->link; - } - } - - //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part - //start the iteration again - temp = min; - min = min->link; - previous = min; - current = min->link; - } -} - -// Test cases: - -// enter the no. of nodes : 5 -// 8 9 3 1 4 -// original list is : 8 9 3 1 4 -// sorted list is : 1 3 4 8 9 - -// enter the no. of nodes : 3 -// -1 -2 -3 -// original list is : -1 -2 -3 -// sorted list is : -3 -2 -1 - -// enter the no. of nodes : 8 -// 8 7 6 5 4 3 2 1 -// original list is : 8 7 6 5 4 3 2 1 -// sorted list is : 1 2 3 4 5 6 7 8 - -// enter the no. of nodes : 6 -// 5 3 4 1 -2 -4 -// original list is : 5 3 4 1 -2 -4 -// sorted list is : -4 -2 1 3 4 5 - -int main() -{ - node *head = NULL; - int n; - cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list - cin >> n; - if (n == 0) - return 0; - head = createlist(n); //creating the list - cout << "original list is : "; - print(head); //printing the original linked list - my_selection_sort_linked_list(head); //applying selection sort - cout << "sorted list is : "; - print(head); //printing the sorted linked list - return 0; -} \ No newline at end of file diff --git a/operations_on_datastructures/selectionsortlinkedlist.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp new file mode 100644 index 000000000..0e8e80def --- /dev/null +++ b/operations_on_datastructures/selectionsortlinkedlist.cpp @@ -0,0 +1,172 @@ +#include +using namespace std; + +// node defined +class node { + public: + int data; + node *link; + node(int d) { + data = d; + link = NULL; + } +}; + +// printing the linked list +void print(node *head) { + node *current = head; + while (current != NULL) { + cout << current->data << " "; + current = current->link; + } + cout << endl; +} + +// creating the linked list with 'n' nodes +node *createlist(int n) { + node *head = NULL; + node *t = NULL; + for (int i = 0; i < n; i++) { + node *temp = NULL; + int num; + cin >> num; + temp = new node(num); + if (head == NULL) { + head = temp; + t = temp; + continue; + } + if (t->link == NULL) + t->link = temp; + t = temp; + } + return head; +} + +// performing selection sort on the linked list in an iterative manner +void my_selection_sort_linked_list(node *&head) { + node *min = head; // throughout the algorithm 'min' is used to denote the + // node with min value out of all the nodes left for + // scanning while scanning if we find a node 'X' with + // value lesser than min, then we update the pointers in + // such a way that 'X' becomes the predecessor of 'min' + node *current = + min->link; // 'current' refers to the current node we are scanning + node *previous = min; //'previous' refers to the node that is previous to + // the current node + node *temp = + NULL; // 'temp' in this algo is used to point to the last node of the + // sorted part of the linked list. + // eg. If at any time instance the state of the linked list is + // suppose 1->2->5->3->8->NULL then, we see that "1->2" is the + // sorted part of the LL, and therefore temp will be pointing to + // the last node of the sorted part,i.e,'2' We keep on arranging + // the Linked list in such a way that after each iteration the + // node with 'min' value is placed at its correct position. Eg. + // Let suppose initially we have 5->4->1->3->2->NULL After 1st + // iteration : 1->4->5->3->2->NULL and so on + + while ( + min->link != + NULL) // so that all the nodes are scanned or until there exists a node + { + // pick the first node from the unsorted part and assume that it is the + // minimum and then start scanning from the next node + + while (current != NULL) // suppose you choose the min node to be X, + // then scan starts from the (X+1)th node until + // its NULL. current = (X+1)th node and min = X + { + if (current->data < min->data) // if the current node is smaller + // than the presumed node 'min' + { + if (temp == NULL) // temp stays null for the first iteration, + // therefore it symbolizes that we are + // scanning for the first time + { + if (previous == + min) // if the 'previous' is pointing to the 'min' node + { + // Update the pointers + head = current; // update the head pointer with the + // current node + min->link = current->link; + current->link = previous; + min = current; + current = previous->link; + } else // if the 'previous' is not pointing to the 'min' + // node + { + // Update the pointers + head = current; // update the head pointer with the + // current node + previous->link = current->link; + current->link = min; + min = current; + current = previous->link; + } + } else // if 'temp' is not NULL, i.e., its not the 1st + // iteration + { + temp->link = current; + previous->link = current->link; + current->link = min; + min = current; + current = previous->link; + } + } else // if the current node is greater than min, just move the + // previous and the current pointer a step further + { + previous = previous->link; + current = current->link; + } + } + + // update the pointers. Set 'temp' to the last node in the sorted part. + // Make 'min' move a step further so that 'min' points to the 1st node + // of the unsorted part start the iteration again + temp = min; + min = min->link; + previous = min; + current = min->link; + } +} + +// Test cases: + +// enter the no. of nodes : 5 +// 8 9 3 1 4 +// original list is : 8 9 3 1 4 +// sorted list is : 1 3 4 8 9 + +// enter the no. of nodes : 3 +// -1 -2 -3 +// original list is : -1 -2 -3 +// sorted list is : -3 -2 -1 + +// enter the no. of nodes : 8 +// 8 7 6 5 4 3 2 1 +// original list is : 8 7 6 5 4 3 2 1 +// sorted list is : 1 2 3 4 5 6 7 8 + +// enter the no. of nodes : 6 +// 5 3 4 1 -2 -4 +// original list is : 5 3 4 1 -2 -4 +// sorted list is : -4 -2 1 3 4 5 + +int main() { + node *head = NULL; + int n; + cout << "enter the no. of nodes : "; // taking input from user about the + // number of nodes in linked list + cin >> n; + if (n == 0) + return 0; + head = createlist(n); // creating the list + cout << "original list is : "; + print(head); // printing the original linked list + my_selection_sort_linked_list(head); // applying selection sort + cout << "sorted list is : "; + print(head); // printing the sorted linked list + return 0; +} \ No newline at end of file diff --git a/operations_on_datastructures/union_of_2_arrays.cpp b/operations_on_datastructures/union_of_2_arrays.cpp new file mode 100644 index 000000000..cdacf1d2e --- /dev/null +++ b/operations_on_datastructures/union_of_2_arrays.cpp @@ -0,0 +1,27 @@ +#include +int main() { + int m, n, i = 0, j = 0; + cout << "Enter size of both arrays:"; + cin >> m >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) cin >> a[i]; + cout << "Enter elements of array 2:"; + for (i = 0; i < n; i++) cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { + if (a[i] < b[j]) + cout << a[i++] << " "; + else if (a[i] > b[j]) + cout << b[j++] << " "; + else { + cout << a[i++]; + j++; + } + } + while (i < m) cout << a[i++] << " "; + while (j < n) cout << b[j++] << " "; + return 0; +} diff --git a/others/decimal_to_roman_numeral.cpp b/others/decimal_to_roman_numeral.cpp index 6bd1be395..ad4aa32c5 100644 --- a/others/decimal_to_roman_numeral.cpp +++ b/others/decimal_to_roman_numeral.cpp @@ -22,22 +22,33 @@ std::string fill(char c, int n) { * the function works recursively */ std::string tolowerRoman(int n) { - if (n < 4) return fill('i', n); - if (n < 6) return fill('i', 5 - n) + "v"; - if (n < 9) return std::string("v") + fill('i', n - 5); - if (n < 11) return fill('i', 10 - n) + "x"; - if (n < 40) return fill('x', n / 10) + tolowerRoman(n % 10); - if (n < 60) return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); + if (n < 4) + return fill('i', n); + if (n < 6) + return fill('i', 5 - n) + "v"; + if (n < 9) + return std::string("v") + fill('i', n - 5); + if (n < 11) + return fill('i', 10 - n) + "x"; + if (n < 40) + return fill('x', n / 10) + tolowerRoman(n % 10); + if (n < 60) + return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); if (n < 90) return std::string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); - if (n < 110) return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); - if (n < 400) return fill('c', n / 100) + tolowerRoman(n % 100); - if (n < 600) return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); + if (n < 110) + return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); + if (n < 400) + return fill('c', n / 100) + tolowerRoman(n % 100); + if (n < 600) + return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); if (n < 900) return std::string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100); - if (n < 1100) return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); - if (n < 4000) return fill('m', n / 1000) + tolowerRoman(n % 1000); + if (n < 1100) + return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); + if (n < 4000) + return fill('m', n / 1000) + tolowerRoman(n % 1000); return "?"; } @@ -45,22 +56,33 @@ std::string tolowerRoman(int n) { * the function works recursively */ std::string toupperRoman(int n) { - if (n < 4) return fill('I', n); - if (n < 6) return fill('I', 5 - n) + "V"; - if (n < 9) return std::string("V") + fill('I', n - 5); - if (n < 11) return fill('I', 10 - n) + "X"; - if (n < 40) return fill('X', n / 10) + toupperRoman(n % 10); - if (n < 60) return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); + if (n < 4) + return fill('I', n); + if (n < 6) + return fill('I', 5 - n) + "V"; + if (n < 9) + return std::string("V") + fill('I', n - 5); + if (n < 11) + return fill('I', 10 - n) + "X"; + if (n < 40) + return fill('X', n / 10) + toupperRoman(n % 10); + if (n < 60) + return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); if (n < 90) return std::string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); - if (n < 110) return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); - if (n < 400) return fill('C', n / 100) + toupperRoman(n % 100); - if (n < 600) return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); + if (n < 110) + return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); + if (n < 400) + return fill('C', n / 100) + toupperRoman(n % 100); + if (n < 600) + return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); if (n < 900) return std::string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100); - if (n < 1100) return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); - if (n < 4000) return fill('M', n / 1000) + toupperRoman(n % 1000); + if (n < 1100) + return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); + if (n < 4000) + return fill('M', n / 1000) + toupperRoman(n % 1000); return "?"; } diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp index 5e7bcb99d..87963c9ad 100644 --- a/others/fast_interger_input.cpp +++ b/others/fast_interger_input.cpp @@ -31,7 +31,8 @@ void fastinput(int *number) { // if scanned input has a negative sign, negate the // value of the input number - if (negative) *(number) *= -1; + if (negative) + *(number) *= -1; } /** Main function */ diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index ef5da6e47..2a6358d94 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -35,14 +35,14 @@ char pop() { return stack[top--]; } */ char opening(char ch) { switch (ch) { - case '}': - return '{'; - case ']': - return '['; - case ')': - return '('; - case '>': - return '<'; + case '}': + return '{'; + case ']': + return '['; + case ')': + return '('; + case '>': + return '<'; } return '\0'; } diff --git a/range_queries/MO.cpp b/range_queries/MO.cpp deleted file mode 100644 index 7172bd632..000000000 --- a/range_queries/MO.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include -using namespace std; -const int N = 1e6 + 5; -int a[N], bucket[N], cnt[N]; -int bucket_size; -struct query -{ - int l, r, i; -} q[N]; -int ans = 0; - -void add(int index) -{ - cnt[a[index]]++; - if (cnt[a[index]] == 1) - ans++; -} -void remove(int index) -{ - cnt[a[index]]--; - if (cnt[a[index]] == 0) - ans--; -} - -bool mycmp(query x, query y) -{ - if (x.l / bucket_size != y.l / bucket_size) - return x.l / bucket_size < y.l / bucket_size; - return x.r < y.r; -} - -int main() -{ - int n, t, i, j, k = 0; - scanf("%d", &n); - for (i = 0; i < n; i++) - scanf("%d", &a[i]); - bucket_size = ceil(sqrt(n)); - scanf("%d", &t); - for (i = 0; i < t; i++) - { - scanf("%d %d", &q[i].l, &q[i].r); - q[i].l--; - q[i].r--; - q[i].i = i; - } - sort(q, q + t, mycmp); - int left = 0, right = 0; - for (i = 0; i < t; i++) - { - int L = q[i].l, R = q[i].r; - while (left < L) - { - remove(left); - left++; - } - while (left > L) - { - add(left - 1); - left--; - } - while (right <= R) - { - add(right); - right++; - } - while (right > R + 1) - { - remove(right - 1); - right--; - } - bucket[q[i].i] = ans; - } - for (i = 0; i < t; i++) - printf("%d\n", bucket[i]); - return 0; -} diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp index e5e36ed24..a1878705b 100644 --- a/range_queries/bit.cpp +++ b/range_queries/bit.cpp @@ -3,66 +3,50 @@ using namespace std; -class Bit -{ +class Bit { int n; vector bit; - inline int offset(int x) - { - return (x & (-x)); - } + inline int offset(int x) { return (x & (-x)); } - public: - - Bit(vector& arr) - { - n = arr.size(); - bit.assign(n + 1, 0); - for (int i = 0; i < n; ++i) - { - update(i, arr[i]); - } + public: + Bit(vector& arr) { + n = arr.size(); + bit.assign(n + 1, 0); + for (int i = 0; i < n; ++i) { + update(i, arr[i]); } - Bit(int x) - { + } + Bit(int x) { n = x; bit.assign(n + 1, 0); } - void update(int id, int val) - { + void update(int id, int val) { // Add val at id id++; - while (id <= n) - { + while (id <= n) { bit[id] += val; id += offset(id); } } - int sum(int id) - { + int sum(int id) { // Get prefix sum upto id. id++; int res = 0; - while (id > 0) - { + while (id > 0) { res += bit[id]; id -= offset(id); } return res; } - int sum_range(int l, int r) - { - return sum(r) - sum(l - 1); - } + int sum_range(int l, int r) { return sum(r) - sum(l - 1); } }; -int main() -{ +int main() { int n = 5; - vector arr = { 1, 2, 3, 4, 5 }; + vector arr = {1, 2, 3, 4, 5}; Bit x(arr); assert(x.sum_range(0, 0) == 1); @@ -72,5 +56,5 @@ int main() assert(x.sum_range(0, 0) == 6); assert(x.sum_range(0, 1) == 8); assert(x.sum_range(0, 2) == 11); - return 0; + return 0; } diff --git a/range_queries/FenwickTree.cpp b/range_queries/fenwicktree.cpp similarity index 70% rename from range_queries/FenwickTree.cpp rename to range_queries/fenwicktree.cpp index a4d1a02de..fb7cbaac4 100644 --- a/range_queries/FenwickTree.cpp +++ b/range_queries/fenwicktree.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; /** @@ -6,43 +6,41 @@ using namespace std; * twos complement works good on this * also using ` x - (x & (x - 1)) ` */ -#define lowbit(x) (x & (-x) ) +#define lowbit(x) (x & (-x)) const int maxn = 1e5 + 7; int tree[maxn] = {0}, - range; // segement of [1...range], notice it must be less than `maxn` + range; // segement of [1...range], notice it must be less than `maxn` void update(int x, int c) { - while(x <= range) { + while (x <= range) { tree[x] += c; x += lowbit(x); } } int query(int x) { int ans = 0; - while(x) { + while (x) { ans += tree[x]; x -= lowbit(x); } return ans; } -int query_segement(int l, int r) { - return query(r) - query(l - 1); -} +int query_segement(int l, int r) { return query(r) - query(l - 1); } int main() { cin >> range; - for(int i = 1; i <= range; i++) { + for (int i = 1; i <= range; i++) { int num; cin >> num; update(i, num); } int q; cin >> q; - while(q--) { + while (q--) { int op; cin >> op; - if(op == 0) { + if (op == 0) { int l, r; cin >> l >> r; cout << query_segement(l, r) << endl; diff --git a/range_queries/mo.cpp b/range_queries/mo.cpp new file mode 100644 index 000000000..d281ef077 --- /dev/null +++ b/range_queries/mo.cpp @@ -0,0 +1,64 @@ +#include +using namespace std; +const int N = 1e6 + 5; +int a[N], bucket[N], cnt[N]; +int bucket_size; +struct query { + int l, r, i; +} q[N]; +int ans = 0; + +void add(int index) { + cnt[a[index]]++; + if (cnt[a[index]] == 1) + ans++; +} +void remove(int index) { + cnt[a[index]]--; + if (cnt[a[index]] == 0) + ans--; +} + +bool mycmp(query x, query y) { + if (x.l / bucket_size != y.l / bucket_size) + return x.l / bucket_size < y.l / bucket_size; + return x.r < y.r; +} + +int main() { + int n, t, i, j, k = 0; + scanf("%d", &n); + for (i = 0; i < n; i++) scanf("%d", &a[i]); + bucket_size = ceil(sqrt(n)); + scanf("%d", &t); + for (i = 0; i < t; i++) { + scanf("%d %d", &q[i].l, &q[i].r); + q[i].l--; + q[i].r--; + q[i].i = i; + } + sort(q, q + t, mycmp); + int left = 0, right = 0; + for (i = 0; i < t; i++) { + int L = q[i].l, R = q[i].r; + while (left < L) { + remove(left); + left++; + } + while (left > L) { + add(left - 1); + left--; + } + while (right <= R) { + add(right); + right++; + } + while (right > R + 1) { + remove(right - 1); + right--; + } + bucket[q[i].i] = ans; + } + for (i = 0; i < t; i++) printf("%d\n", bucket[i]); + return 0; +} diff --git a/range_queries/segTree.cpp b/range_queries/segTree.cpp deleted file mode 100644 index ee81453e1..000000000 --- a/range_queries/segTree.cpp +++ /dev/null @@ -1,92 +0,0 @@ -//#include -#incldue -#define MAX 4000000 -using namespace std; -typedef long long ll; -void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) -{ - if (low == high) - { - segtree[pos] = arr[low]; - return; - } - ll mid = (low + high) / 2; - ConsTree(arr, segtree, low, mid, 2 * pos + 1); - ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); - segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; -} -ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) -{ - if (low > high) - return 0; - if (qlow > high || qhigh < low) - return 0; - if (lazy[pos] != 0) - { - segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += lazy[pos]; - lazy[2 * pos + 2] += lazy[pos]; - } - lazy[pos] = 0; - } - if (qlow <= low && qhigh >= high) - return segtree[pos]; - ll mid = (low + high) / 2; - return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); -} -void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, ll high, ll pos) -{ - if (low > high) - return; - if (lazy[pos] != 0) - { - segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += lazy[pos]; - lazy[2 * pos + 2] += lazy[pos]; - } - lazy[pos] = 0; - } - if (start > high || end < low) - return; - if (start <= low && end >= high) - { - segtree[pos] += delta * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += delta; - lazy[2 * pos + 2] += delta; - } - return; - } - ll mid = (low + high) / 2; - update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); - update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); - segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; -} -int main() -{ - ll n, c; - scanf("%lld %lld", &n, &c); - ll arr[n] = {0}, p, q, v, choice; - ll segtree[MAX], lazy[MAX] = {0}; - ConsTree(arr, segtree, 0, n - 1, 0); - while (c--) - { - scanf("%lld", &choice); - if (choice == 0) - { - scanf("%lld %lld %lld", &p, &q, &v); - update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); - } - else - { - scanf("%lld %lld", &p, &q); - printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); - } - } - return 0; -} diff --git a/range_queries/segtree.cpp b/range_queries/segtree.cpp new file mode 100644 index 000000000..602b3fd95 --- /dev/null +++ b/range_queries/segtree.cpp @@ -0,0 +1,79 @@ +//#include +#incldue < iostream > +#define MAX 4000000 +using namespace std; +typedef long long ll; +void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) { + if (low == high) { + segtree[pos] = arr[low]; + return; + } + ll mid = (low + high) / 2; + ConsTree(arr, segtree, low, mid, 2 * pos + 1); + ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; +} +ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) { + if (low > high) + return 0; + if (qlow > high || qhigh < low) + return 0; + if (lazy[pos] != 0) { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (qlow <= low && qhigh >= high) + return segtree[pos]; + ll mid = (low + high) / 2; + return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); +} +void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, + ll high, ll pos) { + if (low > high) + return; + if (lazy[pos] != 0) { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (start > high || end < low) + return; + if (start <= low && end >= high) { + segtree[pos] += delta * (high - low + 1); + if (low != high) { + lazy[2 * pos + 1] += delta; + lazy[2 * pos + 2] += delta; + } + return; + } + ll mid = (low + high) / 2; + update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); + update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; +} +int main() { + ll n, c; + scanf("%lld %lld", &n, &c); + ll arr[n] = {0}, p, q, v, choice; + ll segtree[MAX], lazy[MAX] = {0}; + ConsTree(arr, segtree, 0, n - 1, 0); + while (c--) { + scanf("%lld", &choice); + if (choice == 0) { + scanf("%lld %lld %lld", &p, &q, &v); + update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); + } else { + scanf("%lld %lld", &p, &q); + printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); + } + } + return 0; +} diff --git a/sorting/Counting_Sort.cpp b/sorting/Counting_Sort.cpp deleted file mode 100644 index bda37bbd8..000000000 --- a/sorting/Counting_Sort.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include -using namespace std; - -int Max(int Arr[], int N) -{ - int max = Arr[0]; - for (int i = 1; i < N; i++) - if (Arr[i] > max) - max = Arr[i]; - return max; -} - -int Min(int Arr[], int N) -{ - int min = Arr[0]; - for (int i = 1; i < N; i++) - if (Arr[i] < min) - min = Arr[i]; - return min; -} - -void Print(int Arr[], int N) -{ - for (int i = 0; i < N; i++) - cout << Arr[i] << ", "; -} - -int *Counting_Sort(int Arr[], int N) -{ - - int max = Max(Arr, N); - int min = Min(Arr, N); - int *Sorted_Arr = new int[N]; - - int *Count = new int[max - min + 1]; - - for (int i = 0; i < N; i++) - Count[Arr[i] - min]++; - - for (int i = 1; i < (max - min + 1); i++) - Count[i] += Count[i - 1]; - - for (int i = N - 1; i >= 0; i--) - { - Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; - Count[Arr[i] - min]--; - } - - return Sorted_Arr; -} - -int main() -{ - - int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; - int *Sorted_Arr; - - cout << "\n\tOrignal Array = "; - Print(Arr, N); - Sorted_Arr = Counting_Sort(Arr, N); - cout << "\n\t Sorted Array = "; - Print(Sorted_Arr, N); - cout << endl; - - return 0; -} diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index a1a54c1e0..f3276bfcd 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -9,7 +9,8 @@ void beadSort(int *a, int len) { // Find the maximum element int max = a[0]; for (int i = 1; i < len; i++) - if (a[i] > max) max = a[i]; + if (a[i] > max) + max = a[i]; // allocating memory unsigned char *beads = new unsigned char[max * len]; diff --git a/sorting/bitonic_sort.cpp b/sorting/bitonic_sort.cpp index 4d0981056..0fbb995ac 100644 --- a/sorting/bitonic_sort.cpp +++ b/sorting/bitonic_sort.cpp @@ -10,7 +10,8 @@ or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/ void compAndSwap(int a[], int i, int j, int dir) { - if (dir == (a[i] > a[j])) std::swap(a[i], a[j]); + if (dir == (a[i] > a[j])) + std::swap(a[i], a[j]); } /*It recursively sorts a bitonic sequence in ascending order, diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp index ab6229996..157acafce 100644 --- a/sorting/cocktail_selection_sort.cpp +++ b/sorting/cocktail_selection_sort.cpp @@ -41,7 +41,8 @@ void CocktailSelectionSort(std::vector *vec, int low, int high) { // Recursive Version void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { - if (low >= high) return; + if (low >= high) + return; int minimum = (*vec)[low]; int minimumindex = low; diff --git a/sorting/counting_sort.cpp b/sorting/counting_sort.cpp new file mode 100644 index 000000000..1fbfc0fa3 --- /dev/null +++ b/sorting/counting_sort.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +int Max(int Arr[], int N) { + int max = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] > max) + max = Arr[i]; + return max; +} + +int Min(int Arr[], int N) { + int min = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] < min) + min = Arr[i]; + return min; +} + +void Print(int Arr[], int N) { + for (int i = 0; i < N; i++) cout << Arr[i] << ", "; +} + +int *Counting_Sort(int Arr[], int N) { + int max = Max(Arr, N); + int min = Min(Arr, N); + int *Sorted_Arr = new int[N]; + + int *Count = new int[max - min + 1]; + + for (int i = 0; i < N; i++) Count[Arr[i] - min]++; + + for (int i = 1; i < (max - min + 1); i++) Count[i] += Count[i - 1]; + + for (int i = N - 1; i >= 0; i--) { + Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; + Count[Arr[i] - min]--; + } + + return Sorted_Arr; +} + +int main() { + int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, + 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, + N = 20; + int *Sorted_Arr; + + cout << "\n\tOrignal Array = "; + Print(Arr, N); + Sorted_Arr = Counting_Sort(Arr, N); + cout << "\n\t Sorted Array = "; + Print(Sorted_Arr, N); + cout << endl; + + return 0; +} diff --git a/sorting/counting_sort_string.cpp b/sorting/counting_sort_string.cpp index 6179e5d11..977f3484d 100644 --- a/sorting/counting_sort_string.cpp +++ b/sorting/counting_sort_string.cpp @@ -3,35 +3,27 @@ using namespace std; -void countSort(string arr) -{ - +void countSort(string arr) { string output; int count[256], i; - for (int i = 0; i < 256; i++) - count[i] = 0; + for (int i = 0; i < 256; i++) count[i] = 0; - for (i = 0; arr[i]; ++i) - ++count[arr[i]]; + for (i = 0; arr[i]; ++i) ++count[arr[i]]; - for (i = 1; i <= 256; ++i) - count[i] += count[i - 1]; + for (i = 1; i <= 256; ++i) count[i] += count[i - 1]; - for (i = 0; arr[i]; ++i) - { + for (i = 0; arr[i]; ++i) { output[count[arr[i]] - 1] = arr[i]; --count[arr[i]]; } - for (i = 0; arr[i]; ++i) - arr[i] = output[i]; + for (i = 0; arr[i]; ++i) arr[i] = output[i]; cout << "Sorted character array is " << arr; } -int main() -{ +int main() { string arr; cin >> arr; diff --git a/sorting/library_sort.cpp b/sorting/library_sort.cpp index 6f1ab6245..c9cba88d8 100644 --- a/sorting/library_sort.cpp +++ b/sorting/library_sort.cpp @@ -8,8 +8,7 @@ void librarySort(int *index, int n) { bool target_lib, *numbered; - for (int i = 0; i < 2; i++) - library[i] = new int[n]; + for (int i = 0; i < 2; i++) library[i] = new int[n]; gaps = new int[n + 1]; numbered = new bool[n + 1]; @@ -79,8 +78,7 @@ int main() { librarySort(index_ex, n_ex); std::cout << "sorted array :" << std::endl; - for (int i = 0; i < n_ex; i++) - std::cout << index_ex[i] << " "; + for (int i = 0; i < n_ex; i++) std::cout << index_ex[i] << " "; std::cout << std::endl; /* --output-- diff --git a/sorting/numeric_string_sort.cpp b/sorting/numeric_string_sort.cpp index 8b86bb29d..04a12e71a 100644 --- a/sorting/numeric_string_sort.cpp +++ b/sorting/numeric_string_sort.cpp @@ -22,7 +22,8 @@ bool NumericSort(std::string a, std::string b) { } int n = a.length(); int m = b.length(); - if (n == m) return a < b; + if (n == m) + return a < b; return n < m; } diff --git a/sorting/odd_even_sort.cpp b/sorting/odd_even_sort.cpp index 62842c174..25f2a3712 100644 --- a/sorting/odd_even_sort.cpp +++ b/sorting/odd_even_sort.cpp @@ -4,58 +4,50 @@ using namespace std; -void oddEven(vector &arr, int size) -{ - bool sorted = false; - while (!sorted) - { - sorted = true; - for (int i = 1; i < size - 1; i += 2) //Odd - { - if (arr[i] > arr[i + 1]) - { - swap(arr[i], arr[i + 1]); - sorted = false; - } - } +void oddEven(vector &arr, int size) { + bool sorted = false; + while (!sorted) { + sorted = true; + for (int i = 1; i < size - 1; i += 2) // Odd + { + if (arr[i] > arr[i + 1]) { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } - for (int i = 0; i < size - 1; i += 2) //Even - { - if (arr[i] > arr[i + 1]) - { - swap(arr[i], arr[i + 1]); - sorted = false; - } - } - } + for (int i = 0; i < size - 1; i += 2) // Even + { + if (arr[i] > arr[i + 1]) { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } + } } -void show(vector A, int size) -{ - int i; - for (i = 0; i < size; i++) - cout << A[i] << "\n"; +void show(vector A, int size) { + int i; + for (i = 0; i < size; i++) cout << A[i] << "\n"; } -int main() -{ - int size, temp; - cout << "\nEnter the number of elements : "; - cin >> size; +int main() { + int size, temp; + cout << "\nEnter the number of elements : "; + cin >> size; - vector arr; + vector arr; - cout << "\nEnter the unsorted elements : \n"; + cout << "\nEnter the unsorted elements : \n"; - for (int i = 0; i < size; ++i) - { - cin >> temp; - arr.push_back(temp); - } + for (int i = 0; i < size; ++i) { + cin >> temp; + arr.push_back(temp); + } - oddEven(arr, size); + oddEven(arr, size); - cout << "Sorted array\n"; - show(arr, size); - return 0; + cout << "Sorted array\n"; + show(arr, size); + return 0; } diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp index 5b8724141..3854f52e6 100644 --- a/sorting/selection_sort.cpp +++ b/sorting/selection_sort.cpp @@ -1,39 +1,33 @@ -//Selection Sort +// Selection Sort #include using namespace std; -int main() -{ - int Array[6]; - cout << "\nEnter any 6 Numbers for Unsorted Array : "; +int main() { + int Array[6]; + cout << "\nEnter any 6 Numbers for Unsorted Array : "; - //Input - for (int i = 0; i < 6; i++) - { - cin >> Array[i]; - } + // 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; - } + // 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"; - } + // Output + cout << "\nSorted Array : "; + for (int i = 0; i < 6; i++) { + cout << Array[i] << "\t"; + } } diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index 1268c7a50..59f204818 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -6,100 +6,105 @@ // for std::swap #include -template void show_data(T *arr, size_t LEN) { - size_t i; +template +void show_data(T *arr, size_t LEN) { + size_t i; - for (i = 0; i < LEN; i++) - std::cout << arr[i] << ", "; - std::cout << std::endl; + for (i = 0; i < LEN; i++) std::cout << arr[i] << ", "; + std::cout << std::endl; } -template void show_data(T (&arr)[N]) { show_data(arr, N); } +template +void show_data(T (&arr)[N]) { + show_data(arr, N); +} /** * Optimized algorithm - takes half the time by utilizing * Mar **/ -template void shell_sort(T *arr, size_t LEN) { - const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; - const unsigned int gap_len = 8; - size_t i, j, g; +template +void shell_sort(T *arr, size_t LEN) { + const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; + const unsigned int gap_len = 8; + size_t i, j, g; - for (g = 0; g < gap_len; g++) { - unsigned int gap = gaps[g]; - for (i = gap; i < LEN; i++) { - T tmp = arr[i]; + for (g = 0; g < gap_len; g++) { + unsigned int gap = gaps[g]; + for (i = gap; i < LEN; i++) { + T tmp = arr[i]; - for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) - arr[j] = arr[j - gap]; + for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) + arr[j] = arr[j - gap]; - arr[j] = tmp; + arr[j] = tmp; + } } - } } -template void shell_sort(T (&arr)[N]) { - shell_sort(arr, N); +template +void shell_sort(T (&arr)[N]) { + shell_sort(arr, N); } /** * function to compare sorting using cstdlib's qsort **/ int compare(const void *a, const void *b) { - int arg1 = *static_cast(a); - int arg2 = *static_cast(b); + int arg1 = *static_cast(a); + int arg2 = *static_cast(b); - if (arg1 < arg2) - return -1; - if (arg1 > arg2) - return 1; - return 0; + if (arg1 < arg2) + return -1; + if (arg1 > arg2) + return 1; + return 0; - // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut - // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) + // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut + // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) } int main(int argc, char *argv[]) { - int i, NUM_DATA; + int i, NUM_DATA; - if (argc == 2) - NUM_DATA = atoi(argv[1]); - else - NUM_DATA = 200; + if (argc == 2) + NUM_DATA = atoi(argv[1]); + else + NUM_DATA = 200; - // int array = new int[NUM_DATA]; - int *data = new int[NUM_DATA]; - int *data2 = new int[NUM_DATA]; - // int array2 = new int[NUM_DATA]; - int range = 1800; + // int array = new int[NUM_DATA]; + int *data = new int[NUM_DATA]; + int *data2 = new int[NUM_DATA]; + // int array2 = new int[NUM_DATA]; + int range = 1800; - std::srand(time(NULL)); - for (i = 0; i < NUM_DATA; i++) - data[i] = data2[i] = (std::rand() % range) - (range >> 1); + std::srand(time(NULL)); + for (i = 0; i < NUM_DATA; i++) + data[i] = data2[i] = (std::rand() % range) - (range >> 1); - std::cout << "Unsorted original data: " << std::endl; - show_data(data, NUM_DATA); - std::clock_t start = std::clock(); - shell_sort(data, NUM_DATA); - std::clock_t end = std::clock(); + std::cout << "Unsorted original data: " << std::endl; + show_data(data, NUM_DATA); + std::clock_t start = std::clock(); + shell_sort(data, NUM_DATA); + std::clock_t end = std::clock(); - std::cout << std::endl - << "Data Sorted using custom implementation: " << std::endl; - show_data(data, NUM_DATA); + std::cout << std::endl + << "Data Sorted using custom implementation: " << std::endl; + show_data(data, NUM_DATA); - double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; - std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - start = std::clock(); - qsort(data2, NUM_DATA, sizeof(data2[0]), compare); - end = std::clock(); - std::cout << "Data Sorted using cstdlib qsort: " << std::endl; - show_data(data2, NUM_DATA); + start = std::clock(); + qsort(data2, NUM_DATA, sizeof(data2[0]), compare); + end = std::clock(); + std::cout << "Data Sorted using cstdlib qsort: " << std::endl; + show_data(data2, NUM_DATA); - elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; - std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - free(data); - free(data2); - return 0; + free(data); + free(data2); + return 0; } diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index b2627d12f..a3e64dba0 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -11,7 +11,8 @@ #include void SlowSort(int a[], int i, int j) { - if (i >= j) return; + if (i >= j) + return; int m = i + (j - i) / 2; // midpoint, implemented this way to avoid // overflow int temp; diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index 2e59e2fb3..4cdaa57b3 100644 --- a/sorting/swap_sort.cpp +++ b/sorting/swap_sort.cpp @@ -32,7 +32,8 @@ int minSwaps(int arr[], int n) { for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos - if (vis[i] || arrPos[i].second == i) continue; + if (vis[i] || arrPos[i].second == i) + continue; // find out the number of node in // this cycle and add in ans