├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── pull_request_template.md └── workflows │ ├── build.yml │ ├── prettify.yml │ ├── stale.yml │ └── update_directory.yml ├── .gitignore ├── .gitpod.Dockerfile ├── .gitpod.yml ├── CONTRIBUTING.md ├── DIRECTORY.md ├── LICENSE ├── README-ko.md ├── README.md ├── pom.xml └── src ├── main └── java │ └── com │ └── thealgorithms │ ├── audiofilters │ └── IIRFilter.java │ ├── backtracking │ ├── KnightsTour.java │ ├── NQueens.java │ └── PowerSum.java │ ├── ciphers │ ├── AES.java │ ├── AESEncryption.java │ ├── AffineCipher.java │ ├── Caesar.java │ ├── ColumnarTranspositionCipher.java │ ├── HillCipher.java │ ├── ProductCipher.java │ ├── RSA.java │ ├── SimpleSubCipher.java │ ├── SimpleSubstitutionCipher.java │ └── Vigenere.java │ ├── conversions │ ├── AnyBaseToAnyBase.java │ ├── AnyBaseToDecimal.java │ ├── AnytoAny.java │ ├── BinaryToDecimal.java │ ├── BinaryToHexadecimal.java │ ├── BinaryToOctal.java │ ├── DecimalToAnyBase.java │ ├── DecimalToBinary.java │ ├── DecimalToHexaDecimal.java │ ├── DecimalToOctal.java │ ├── HexToOct.java │ ├── HexaDecimalToBinary.java │ ├── HexaDecimalToDecimal.java │ ├── IntegerToRoman.java │ ├── OctalToDecimal.java │ ├── OctalToHexadecimal.java │ ├── RgbHsvConversion.java │ ├── RomanToInteger.java │ └── TurkishToLatinConversion.java │ ├── datastructures │ ├── bags │ │ └── Bag.java │ ├── buffers │ │ └── CircularBuffer.java │ ├── caches │ │ ├── LRUCache.java │ │ └── MRUCache.java │ ├── disjointsets │ │ ├── DisjointSets.java │ │ └── Node.java │ ├── dynamicarray │ │ └── DynamicArray.java │ ├── graphs │ │ ├── A_Star.java │ │ ├── BellmanFord.java │ │ ├── BipartiteGrapfDFS.java │ │ ├── ConnectedComponent.java │ │ ├── Cycles.java │ │ ├── DIJSKSTRAS_ALGORITHM.java │ │ ├── FloydWarshall.java │ │ ├── Graphs.java │ │ ├── KahnsAlgorithm.java │ │ ├── Kruskal.java │ │ ├── MatrixGraphs.java │ │ ├── PrimMST.java │ │ └── README.md │ ├── hashmap │ │ ├── Readme.md │ │ └── hashing │ │ │ ├── HashMap.java │ │ │ ├── HashMapLinearProbing.java │ │ │ ├── Intersection │ │ │ ├── Main.java │ │ │ └── MainLinearProbing.java │ ├── heaps │ │ ├── EmptyHeapException.java │ │ ├── GenericHeap │ │ ├── Heap.java │ │ ├── HeapElement.java │ │ ├── MaxHeap.java │ │ ├── MinHeap.java │ │ ├── MinPriorityQueue.java │ │ └── Readme.md │ ├── lists │ │ ├── CircleLinkedList.java │ │ ├── CountSinglyLinkedListRecursion.java │ │ ├── CreateAndDetectLoop.java │ │ ├── CursorLinkedList.java │ │ ├── DoublyLinkedList.java │ │ ├── MergeSortedArrayList.java │ │ ├── MergeSortedSinglyLinkedList.java │ │ ├── Merge_K_SortedLinkedlist.java │ │ ├── README.md │ │ ├── RandomNode.java │ │ ├── RemoveDuplicateNodes.java │ │ ├── SearchSinglyLinkedListRecursion.java │ │ └── SinglyLinkedList.java │ ├── queues │ │ ├── CircularQueue.java │ │ ├── Deques.java │ │ ├── GenericArrayListQueue.java │ │ ├── LinkedQueue.java │ │ ├── PriorityQueues.java │ │ ├── Queues.java │ │ └── README.md │ ├── stacks │ │ ├── BalancedBrackets.java │ │ ├── DecimalToAnyUsingStack.java │ │ ├── DuplicateBrackets.java │ │ ├── InfixToPostfix.java │ │ ├── MaximumMinimumWindow.java │ │ ├── NextGraterElement.java │ │ ├── NextSmallerElement.java │ │ ├── NodeStack.java │ │ ├── README.md │ │ ├── ReverseStack.java │ │ ├── StackArray.java │ │ ├── StackArrayList.java │ │ └── StackOfLinkedList.java │ └── trees │ │ ├── AVLSimple │ │ ├── AVLTree.java │ │ ├── BSTIterative.java │ │ ├── BSTRecursive.java │ │ ├── BSTRecursiveGeneric.java │ │ ├── BinaryTree.java │ │ ├── CeilInBinarySearchTree.java │ │ ├── CheckIfBinaryTreeBalanced.java │ │ ├── CreateBSTFromSortedArray.java │ │ ├── CreateBinaryTreeFromInorderPreorder.java │ │ ├── FenwickTree.java │ │ ├── GenericTree.java │ │ ├── LCA.java │ │ ├── LevelOrderTraversal.java │ │ ├── LevelOrderTraversalQueue.java │ │ ├── PrintTopViewofTree.java │ │ ├── README.md │ │ ├── RedBlackBST.java │ │ ├── SegmentTree.java │ │ ├── TreeTraversal.java │ │ ├── TrieImp.java │ │ ├── ValidBSTOrNot.java │ │ ├── VerticalOrderTraversal.java │ │ └── nearestRightKey.java │ ├── devutils │ ├── nodes │ │ ├── LargeTreeNode.java │ │ ├── Node.java │ │ ├── SimpleNode.java │ │ ├── SimpleTreeNode.java │ │ └── TreeNode.java │ └── searches │ │ └── SearchAlgorithm.java │ ├── divideandconquer │ ├── BinaryExponentiation.java │ ├── ClosestPair.java │ ├── SkylineAlgorithm.java │ └── StrassenMatrixMultiplication.java │ ├── dynamicprogramming │ ├── BoardPath.java │ ├── BoundaryFill.java │ ├── BruteForceKnapsack.java │ ├── CatalanNumber.java │ ├── CoinChange.java │ ├── DiceThrow.java │ ├── DyanamicProgrammingKnapsack.java │ ├── EditDistance.java │ ├── EggDropping.java │ ├── Fibonacci.java │ ├── FloodFill.java │ ├── FordFulkerson.java │ ├── KadaneAlgorithm.java │ ├── Knapsack.java │ ├── KnapsackMemoization.java │ ├── LevenshteinDistance.java │ ├── LongestAlternatingSubsequence.java │ ├── LongestCommonSubsequence.java │ ├── LongestIncreasingSubsequence.java │ ├── LongestPalindromicSubsequence.java │ ├── LongestPalindromicSubstring.java │ ├── LongestValidParentheses.java │ ├── MatrixChainMultiplication.java │ ├── MatrixChainRecursiveTopDownMemoisation.java │ ├── MemoizationTechniqueKnapsack.java │ ├── MinimumPathSum.java │ ├── MinimumSumPartition.java │ ├── PalindromicPartitioning.java │ ├── RegexMatching.java │ ├── RodCutting.java │ ├── ShortestCommonSupersequenceLength.java │ ├── SubsetSum.java │ ├── Sum_Of_Subset.java │ └── WineProblem.java │ ├── maths │ ├── ADTFraction.java │ ├── AbsoluteMax.java │ ├── AbsoluteMin.java │ ├── AbsoluteValue.java │ ├── AliquotSum.java │ ├── AmicableNumber.java │ ├── Area.java │ ├── Armstrong.java │ ├── AutomorphicNumber.java │ ├── Average.java │ ├── BinaryPow.java │ ├── BinomialCoefficient.java │ ├── Ceil.java │ ├── CircularConvolutionFFT.java │ ├── Combinations.java │ ├── Convolution.java │ ├── ConvolutionFFT.java │ ├── DeterminantOfMatrix.java │ ├── DigitalRoot.java │ ├── DudeneyNumber.java │ ├── EulerMethod.java │ ├── FFT.java │ ├── FFTBluestein.java │ ├── Factorial.java │ ├── FactorialRecursion.java │ ├── FibonacciJavaStreams.java │ ├── FibonacciNumber.java │ ├── FindMax.java │ ├── FindMaxRecursion.java │ ├── FindMin.java │ ├── FindMinRecursion.java │ ├── Floor.java │ ├── GCD.java │ ├── GCDRecursion.java │ ├── Gaussian.java │ ├── GenericRoot.java │ ├── HarshadNumber.java │ ├── JugglerSequence.java │ ├── KaprekarNumbers.java │ ├── KeithNumber.java │ ├── KrishnamurthyNumber.java │ ├── LeonardoNumber.java │ ├── LinearDiophantineEquationsSolver.java │ ├── LucasSeries.java │ ├── MagicSquare.java │ ├── MatrixUtil.java │ ├── MaxValue.java │ ├── Median.java │ ├── MinValue.java │ ├── Mode.java │ ├── NonRepeatingElement.java │ ├── NthUglyNumber.java │ ├── NumberOfDigits.java │ ├── PalindromeNumber.java │ ├── ParseInteger.java │ ├── PascalTriangle.java │ ├── PerfectCube.java │ ├── PerfectNumber.java │ ├── PerfectSquare.java │ ├── PiNilakantha.java │ ├── Pow.java │ ├── PowRecursion.java │ ├── PowerOfTwoOrNot.java │ ├── PrimeCheck.java │ ├── PrimeFactorization.java │ ├── PronicNumber.java │ ├── PythagoreanTriple.java │ ├── ReverseNumber.java │ ├── RomanNumeralUtil.java │ ├── SimpsonIntegration.java │ ├── SumOfArithmeticSeries.java │ ├── SumOfDigits.java │ ├── TrinomialTriangle.java │ ├── VampireNumber.java │ ├── VectorCrossProduct.java │ └── Volume.java │ ├── matrixexponentiation │ └── Fibonacci.java │ ├── minimizinglateness │ ├── MinimizingLateness.java │ └── lateness_data.txt │ ├── misc │ ├── ColorContrastRatio.java │ ├── InverseOfMatrix.java │ ├── MedianOfRunningArray.java │ ├── PalindromePrime.java │ ├── PalindromeSinglyLinkedList.java │ ├── RangeInSortedArray.java │ ├── Sort012D.java │ ├── Sparcity.java │ ├── ThreeSumProblem.java │ ├── TwoSumProblem.java │ ├── WordBoggle.java │ └── matrixTranspose.java │ ├── others │ ├── ArrayLeftRotation.java │ ├── BFPRT.java │ ├── BankersAlgorithm.java │ ├── BestFit.java │ ├── BoyerMoore.java │ ├── BrianKernighanAlgorithm.java │ ├── CRC32.java │ ├── CRCAlgorithm.java │ ├── CountChar.java │ ├── CountWords.java │ ├── Damm.java │ ├── Dijkstra.java │ ├── EulersFunction.java │ ├── FibbonaciSeries.java │ ├── FirstFit.java │ ├── FloydTriangle.java │ ├── GuassLegendre.java │ ├── HappyNumbersSeq.java │ ├── Huffman.java │ ├── Implementing_auto_completing_features_using_trie.java │ ├── InsertDeleteInArray.java │ ├── KMP.java │ ├── KochSnowflake.java │ ├── Krishnamurthy.java │ ├── LinearCongruentialGenerator.java │ ├── LowestBasePalindrome.java │ ├── Luhn.java │ ├── Mandelbrot.java │ ├── MiniMaxAlgorithm.java │ ├── PageRank.java │ ├── PasswordGen.java │ ├── PerlinNoise.java │ ├── QueueUsingTwoStacks.java │ ├── RabinKarp.java │ ├── RemoveDuplicateFromString.java │ ├── ReturnSubsequence.java │ ├── ReverseStackUsingRecursion.java │ ├── RootPrecision.java │ ├── RotateMatriceBy90Degree.java │ ├── SJF.java │ ├── SieveOfEratosthenes.java │ ├── SkylineProblem.java │ ├── StackPostfixNotation.java │ ├── StringMatchFiniteAutomata.java │ ├── Sudoku.java │ ├── ThreeSum.java │ ├── TopKWords.java │ ├── TowerOfHanoi.java │ ├── TwoPointers.java │ ├── Verhoeff.java │ └── WorstFit.java │ ├── searches │ ├── BinarySearch.java │ ├── BreadthFirstSearch.java │ ├── DepthFirstSearch.java │ ├── ExponentalSearch.java │ ├── FibonacciSearch.java │ ├── HowManyTimesRotated.java │ ├── InterpolationSearch.java │ ├── IterativeBinarySearch.java │ ├── IterativeTernarySearch.java │ ├── JumpSearch.java │ ├── LinearSearch.java │ ├── LinearSearchThread.java │ ├── LowerBound.java │ ├── MonteCarloTreeSearch.java │ ├── PerfectBinarySearch.java │ ├── QuickSelect.java │ ├── SaddlebackSearch.java │ ├── SquareRootBinarySearch.java │ ├── TernarySearch.java │ ├── UnionFind.java │ └── UpperBound.java │ ├── sorts │ ├── BitonicSort.java │ ├── BogoSort.java │ ├── BubbleSort.java │ ├── BubbleSortRecursion.java │ ├── BucketSort.java │ ├── CircleSort.java │ ├── CocktailShakerSort.java │ ├── CombSort.java │ ├── CountingSort.java │ ├── CycleSort.java │ ├── DNFSort.java │ ├── GnomeSort.java │ ├── HeapSort.java │ ├── InsertionSort.java │ ├── MergeSort.java │ ├── MergeSortNoExtraSpace.java │ ├── MergeSortRecursive.java │ ├── OddEvenSort.java │ ├── PancakeSort.java │ ├── QuickSort.java │ ├── RadixSort.java │ ├── SelectionSort.java │ ├── ShellSort.java │ ├── SimpleSort.java │ ├── SlowSort.java │ ├── SortAlgorithm.java │ ├── SortUtils.java │ ├── StoogeSort.java │ ├── SwapSort.java │ ├── TimSort.java │ └── TreeSort.java │ └── strings │ ├── Alphabetical.java │ ├── Anagrams.java │ ├── CharactersSame.java │ ├── CheckAnagrams.java │ ├── CheckVowels.java │ ├── HorspoolSearch.java │ ├── List_all_Possible_Words_From_Phone_Digits.java │ ├── LongestPalindromicSubstring.java │ ├── Lower.java │ ├── Palindrome.java │ ├── Pangram.java │ ├── PermuteString.java │ ├── ReverseString.java │ ├── Rotation.java │ ├── Upper.java │ └── WordLadder.java └── test └── java └── com └── thealgorithms ├── maths ├── KaprekarNumbersTest.java ├── PascalTriangleTest.java └── PronicNumberTest.java ├── others └── ArrayLeftRotationTest.java └── searches └── QuickSelectTest.java /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @siriak @yanglbme 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Device Specification** 27 | 28 | **Additional context** 29 | Add any other context about the problem here. 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### **Describe your change:** 2 | 3 | - [ ] Add an algorithm? 4 | - [ ] Fix a bug or typo in an existing algorithm? 5 | - [ ] Documentation change? 6 | 7 | #### References 8 | 9 | 10 | 11 | ### **Checklist:** 12 | 13 | 14 | 15 | - [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md). 16 | - [ ] This pull request is all my own work -- I have not plagiarized. 17 | - [ ] I know that pull requests will not be merged if they fail the automated tests. 18 | - [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. 19 | - [ ] All new Java files are placed inside an existing directory. 20 | - [ ] All filenames are in all uppercase characters with no spaces or dashes. 21 | - [ ] All functions and variable names follow Java naming conventions. 22 | - [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. 23 | - [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. 24 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: [push, pull_request] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | - name: Set up JDK 17 9 | uses: actions/setup-java@v2 10 | with: 11 | java-version: 17 12 | distribution: 'adopt' 13 | - name: Build with Maven 14 | run: mvn --batch-mode --update-snapshots verify 15 | -------------------------------------------------------------------------------- /.github/workflows/prettify.yml: -------------------------------------------------------------------------------- 1 | name: Prettify 2 | on: [push, pull_request] 3 | jobs: 4 | prettier: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout 8 | uses: actions/checkout@v2 9 | with: 10 | ref: ${{ github.head_ref }} 11 | 12 | - name: Prettify code 13 | uses: creyD/prettier_action@v3.3 14 | with: 15 | prettier_options: --write **/*.java 16 | commit_message: 'Prettify code' 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: 'Close stale issues and PRs' 2 | on: 3 | schedule: 4 | - cron: '0 0 * * *' 5 | jobs: 6 | stale: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/stale@v4 10 | with: 11 | stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' 12 | close-issue-message: 'Please reopen this issue once you add more information and updates here. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!' 13 | stale-pr-message: 'This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' 14 | close-pr-message: 'Please reopen this pull request once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!' 15 | exempt-issue-labels: 'dont-close' 16 | exempt-pr-labels: 'dont-close' 17 | days-before-stale: 30 18 | days-before-close: 7 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /gradle/wrapper/gradle-wrapper.properties 2 | ##----------Android---------- 3 | # build 4 | *.apk 5 | *.ap_ 6 | *.dex 7 | *.class 8 | bin/ 9 | gen/ 10 | build/ 11 | out/ 12 | 13 | # gradle 14 | .gradle/ 15 | gradle-app.setting 16 | !gradle-wrapper.jar 17 | build/ 18 | 19 | # maven 20 | *.classpath 21 | *.project 22 | *.settings 23 | /target/ 24 | 25 | local.properties 26 | 27 | ##----------idea---------- 28 | *.iml 29 | .idea/ 30 | *.ipr 31 | *.iws 32 | 33 | # Android Studio Navigation editor temp files 34 | .navigation/ 35 | 36 | ##----------Other---------- 37 | # osx 38 | *~ 39 | .DS_Store 40 | gradle.properties 41 | 42 | .vscode 43 | 44 | *.log 45 | -------------------------------------------------------------------------------- /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full 2 | 3 | # Install custom tools, runtimes, etc. 4 | # For example "bastet", a command-line tetris clone: 5 | # RUN brew install bastet 6 | # 7 | # More information: https://www.gitpod.io/docs/config-docker/ 8 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: 2 | file: .gitpod.Dockerfile 3 | 4 | tasks: 5 | - init: 'echo "TODO: Replace with init/build command"' 6 | command: (e.g. 'npm start', 'yarn watch'...) 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 The Algorithms 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Algorithms - Java 2 | 3 | [![Build](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml) 4 | [![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://discord.gg/c7MnfGFGa6) 5 | [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) 6 | 7 | 8 | You can run and edit the algorithms, or contribute to them using Gitpod.io (a free online development environment) with a single click. 9 | 10 | [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) 11 | 12 | ### All algorithms are implemented in Java (for educational purposes) 13 | These implementations are intended for learning purposes. As such, they may be less efficient than the Java standard library. 14 | 15 | ## Contribution Guidelines 16 | Please read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute to this project. 17 | 18 | ## Community Channel 19 | We're on [Gitter](https://gitter.im/TheAlgorithms)! Come join us. 20 | 21 | ## Algorithms 22 | Our [directory](DIRECTORY.md) has the full list of applications. 23 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | com.thealgorithms 7 | Java 8 | 1.0-SNAPSHOT 9 | jar 10 | 11 | UTF-8 12 | 17 13 | 17 14 | 15 | 16 | 17 | 18 | 19 | org.junit 20 | junit-bom 21 | 5.8.2 22 | pom 23 | import 24 | 25 | 26 | 27 | 28 | 29 | 30 | org.junit.jupiter 31 | junit-jupiter 32 | test 33 | 34 | 35 | 36 | 37 | 38 | 39 | maven-compiler-plugin 40 | 3.8.1 41 | 42 | 43 | maven-surefire-plugin 44 | 2.22.2 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/AnytoAny.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | // given a source number , source base, destination base, this code can give you the destination 5 | // number. 6 | // sn ,sb,db ---> ()dn . this is what we have to do . 7 | 8 | public class AnytoAny { 9 | 10 | public static void main(String[] args) { 11 | Scanner scn = new Scanner(System.in); 12 | int sn = scn.nextInt(); 13 | int sb = scn.nextInt(); 14 | int db = scn.nextInt(); 15 | int m = 1, dec = 0, dn = 0; 16 | while (sn != 0) { 17 | dec = dec + (sn % 10) * m; 18 | m *= sb; 19 | sn /= 10; 20 | } 21 | m = 1; 22 | while (dec != 0) { 23 | dn = dn + (dec % db) * m; 24 | m *= 10; 25 | dec /= db; 26 | } 27 | System.out.println(dn); 28 | scn.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Binary number to a Decimal number 7 | */ 8 | class BinaryToDecimal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line arguments 14 | */ 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int binNum, binCopy, d, s = 0, power = 0; 18 | System.out.print("Binary number: "); 19 | binNum = sc.nextInt(); 20 | binCopy = binNum; 21 | while (binCopy != 0) { 22 | d = binCopy % 10; 23 | s += d * (int) Math.pow(2, power++); 24 | binCopy /= 10; 25 | } 26 | System.out.println("Decimal equivalent:" + s); 27 | sc.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/BinaryToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Binary number to an Octal Number 7 | * 8 | * @author Zachary Jones 9 | */ 10 | public class BinaryToOctal { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.println("Input the binary number: "); 20 | int b = sc.nextInt(); 21 | System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); 22 | sc.close(); 23 | } 24 | 25 | /** 26 | * This method converts a binary number to an octal number. 27 | * 28 | * @param binary The binary number 29 | * @return The octal number 30 | */ 31 | public static String convertBinaryToOctal(int binary) { 32 | String octal = ""; 33 | int currBit = 0, j = 1; 34 | while (binary != 0) { 35 | int code3 = 0; 36 | for (int i = 0; i < 3; i++) { 37 | currBit = binary % 10; 38 | binary = binary / 10; 39 | code3 += currBit * j; 40 | j *= 2; 41 | } 42 | octal = code3 + octal; 43 | j = 1; 44 | } 45 | return octal; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/DecimalToBinary.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Decimal number to a Binary number 7 | */ 8 | class DecimalToBinary { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command Line Arguments 14 | */ 15 | public static void main(String args[]) { 16 | conventionalConversion(); 17 | bitwiseConversion(); 18 | } 19 | 20 | /** 21 | * This method converts a decimal number to a binary number using a 22 | * conventional algorithm. 23 | */ 24 | public static void conventionalConversion() { 25 | int n, b = 0, c = 0, d; 26 | Scanner input = new Scanner(System.in); 27 | System.out.printf("Conventional conversion.%n Enter the decimal number: "); 28 | n = input.nextInt(); 29 | while (n != 0) { 30 | d = n % 2; 31 | b = b + d * (int) Math.pow(10, c++); 32 | n /= 2; 33 | } // converting decimal to binary 34 | System.out.println("\tBinary number: " + b); 35 | input.close(); 36 | } 37 | 38 | /** 39 | * This method converts a decimal number to a binary number using a bitwise 40 | * algorithm 41 | */ 42 | public static void bitwiseConversion() { 43 | int n, b = 0, c = 0, d; 44 | Scanner input = new Scanner(System.in); 45 | System.out.printf("Bitwise conversion.%n Enter the decimal number: "); 46 | n = input.nextInt(); 47 | while (n != 0) { 48 | d = (n & 1); 49 | b += d * (int) Math.pow(10, c++); 50 | n >>= 1; 51 | } 52 | System.out.println("\tBinary number: " + b); 53 | input.close(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | // hex = [0 - 9] -> [A - F] 4 | class DecimalToHexaDecimal { 5 | 6 | private static final int sizeOfIntInHalfBytes = 8; 7 | private static final int numberOfBitsInAHalfByte = 4; 8 | private static final int halfByte = 0x0F; 9 | private static final char[] hexDigits = { 10 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 11 | }; 12 | 13 | // Returns the hex value of the dec entered in the parameter. 14 | public static String decToHex(int dec) { 15 | StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); 16 | hexBuilder.setLength(sizeOfIntInHalfBytes); 17 | for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) { 18 | int j = dec & halfByte; 19 | hexBuilder.setCharAt(i, hexDigits[j]); 20 | dec >>= numberOfBitsInAHalfByte; 21 | } 22 | return hexBuilder.toString().toLowerCase(); 23 | } 24 | 25 | // Test above function. 26 | public static void main(String[] args) { 27 | System.out.println("Test..."); 28 | int dec = 305445566; 29 | String libraryDecToHex = Integer.toHexString(dec); 30 | String decToHex = decToHex(dec); 31 | System.out.println("Result from the library : " + libraryDecToHex); 32 | System.out.println("Result decToHex method : " + decToHex); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/DecimalToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts Decimal numbers to Octal Numbers 7 | */ 8 | public class DecimalToOctal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line Arguments 14 | */ 15 | 16 | // enter in a decimal value to get Octal output 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n, k, d, s = 0, c = 0; 20 | System.out.print("Decimal number: "); 21 | n = sc.nextInt(); 22 | k = n; 23 | while (k != 0) { 24 | d = k % 8; 25 | s += d * (int) Math.pow(10, c++); 26 | k /= 8; 27 | } 28 | 29 | System.out.println("Octal equivalent:" + s); 30 | sc.close(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | // Hex [0-9],[A-F] -> Binary [0,1] 4 | public class HexaDecimalToBinary { 5 | 6 | private final int LONG_BITS = 8; 7 | 8 | public void convert(String numHex) { 9 | // String a HexaDecimal: 10 | int conHex = Integer.parseInt(numHex, 16); 11 | // Hex a Binary: 12 | String binary = Integer.toBinaryString(conHex); 13 | // Output: 14 | System.out.println(numHex + " = " + completeDigits(binary)); 15 | } 16 | 17 | public String completeDigits(String binNum) { 18 | for (int i = binNum.length(); i < LONG_BITS; i++) { 19 | binNum = "0" + binNum; 20 | } 21 | return binNum; 22 | } 23 | 24 | public static void main(String[] args) { 25 | 26 | // Testing Numbers: 27 | String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"}; 28 | HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); 29 | 30 | for (String num : hexNums) { 31 | objConvert.convert(num); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class HexaDecimalToDecimal { 6 | 7 | // convert hexadecimal to decimal 8 | public static int getHexaToDec(String hex) { 9 | String digits = "0123456789ABCDEF"; 10 | hex = hex.toUpperCase(); 11 | int val = 0; 12 | for (int i = 0; i < hex.length(); i++) { 13 | int d = digits.indexOf(hex.charAt(i)); 14 | val = 16 * val + d; 15 | } 16 | return val; 17 | } 18 | 19 | // Main method gets the hexadecimal input from user and converts it into Decimal output. 20 | public static void main(String args[]) { 21 | String hexa_Input; 22 | int dec_output; 23 | Scanner scan = new Scanner(System.in); 24 | 25 | System.out.print("Enter Hexadecimal Number : "); 26 | hexa_Input = scan.nextLine(); 27 | 28 | // convert hexadecimal to decimal 29 | dec_output = getHexaToDec(hexa_Input); 30 | /* 31 | Pass the string to the getHexaToDec function 32 | and it returns the decimal form in the variable dec_output. 33 | */ 34 | System.out.println("Number in Decimal: " + dec_output); 35 | scan.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | /** 4 | * Converting Integers into Roman Numerals 5 | * 6 | *

7 | * ('I', 1); ('IV',4); ('V', 5); ('IX',9); ('X', 10); ('XL',40); ('L', 50); 8 | * ('XC',90); ('C', 100); ('D', 500); ('M', 1000); 9 | */ 10 | public class IntegerToRoman { 11 | 12 | private static int[] allArabianRomanNumbers 13 | = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 14 | private static String[] allRomanNumbers 15 | = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 16 | 17 | // Value must be > 0 18 | public static String integerToRoman(int num) { 19 | if (num <= 0) { 20 | return ""; 21 | } 22 | 23 | StringBuilder builder = new StringBuilder(); 24 | 25 | for (int a = 0; a < allArabianRomanNumbers.length; a++) { 26 | int times = num / allArabianRomanNumbers[a]; 27 | for (int b = 0; b < times; b++) { 28 | builder.append(allRomanNumbers[a]); 29 | } 30 | 31 | num -= times * allArabianRomanNumbers[a]; 32 | } 33 | 34 | return builder.toString(); 35 | } 36 | 37 | public static void main(String[] args) { 38 | System.out.println(IntegerToRoman.integerToRoman(2131)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/OctalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Octal Number to a Decimal Number 7 | * 8 | * @author Zachary Jones 9 | */ 10 | public class OctalToDecimal { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.print("Octal Input: "); 20 | String inputOctal = sc.nextLine(); 21 | int result = convertOctalToDecimal(inputOctal); 22 | if (result != -1) { 23 | System.out.println("Result convertOctalToDecimal : " + result); 24 | } 25 | sc.close(); 26 | } 27 | 28 | /** 29 | * This method converts an octal number to a decimal number. 30 | * 31 | * @param inputOctal The octal number 32 | * @return The decimal number 33 | */ 34 | public static int convertOctalToDecimal(String inputOctal) { 35 | 36 | try { 37 | // Actual conversion of Octal to Decimal: 38 | Integer outputDecimal = Integer.parseInt(inputOctal, 8); 39 | return outputDecimal; 40 | } catch (NumberFormatException ne) { 41 | // Printing a warning message if the input is not a valid octal 42 | // number: 43 | System.out.println("Invalid Input, Expecting octal number 0-7"); 44 | return -1; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts turkish character to latin character 7 | * 8 | * @author Özgün Gökşenli 9 | */ 10 | public class TurkishToLatinConversion { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.println("Input the string: "); 20 | String b = sc.next(); 21 | System.out.println("Converted: " + convertTurkishToLatin(b)); 22 | sc.close(); 23 | } 24 | 25 | /** 26 | * This method converts a turkish character to latin character. 27 | * 28 | * @param param String paramter 29 | * @return String 30 | */ 31 | public static String convertTurkishToLatin(String param) { 32 | char[] turkishChars 33 | = new char[]{0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E}; 34 | char[] latinChars = new char[]{'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'}; 35 | for (int i = 0; i < turkishChars.length; i++) { 36 | param 37 | = param.replaceAll( 38 | new String(new char[]{turkishChars[i]}), new String(new char[]{latinChars[i]})); 39 | } 40 | return param; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/disjointsets/DisjointSets.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.disjointsets; 2 | 3 | public class DisjointSets { 4 | 5 | public Node MakeSet(T x) { 6 | return new Node(x); 7 | } 8 | 9 | ; 10 | 11 | public Node FindSet(Node node) { 12 | if (node != node.parent) { 13 | node.parent = FindSet(node.parent); 14 | } 15 | 16 | return node.parent; 17 | } 18 | 19 | public void UnionSet(Node x, Node y) { 20 | Node nx = FindSet(x); 21 | Node ny = FindSet(y); 22 | 23 | if (nx == ny) { 24 | return; 25 | } 26 | if (nx.rank > ny.rank) { 27 | ny.parent = nx; 28 | } else if (ny.rank > nx.rank) { 29 | nx.parent = ny; 30 | } else { 31 | nx.parent = ny; 32 | ny.rank++; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/disjointsets/Node.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.disjointsets; 2 | 3 | public class Node { 4 | 5 | public int rank; 6 | public Node parent; 7 | public T data; 8 | 9 | public Node(T data) { 10 | this.data = data; 11 | parent = this; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/graphs/README.md: -------------------------------------------------------------------------------- 1 | ## Graph 2 | 3 | Graph is a useful data structure for representing most of the real world problems involving a set of users/candidates/nodes and their relations. A Graph consists of two parameters : 4 | 5 | ``` 6 | V = a set of vertices 7 | E = a set of edges 8 | ``` 9 | 10 | Each edge in `E` connects any two vertices from `V`. Based on the type of edge, graphs can be of two types: 11 | 12 | 1. **Directed**: The edges are directed in nature which means that when there is an edge from node `A` to `B`, it does not imply that there is an edge from `B` to `A`. 13 | An example of directed edge graph the **follow** feature of social media. If you follow a celebrity, it doesn't imply that s/he follows you. 14 | 15 | 2. **Undirected**: The edges don't have any direction. So if `A` and `B` are connected, we can assume that there is edge from both `A` to `B` and `B` to `A`. 16 | Example: Social media graph, where if two persons are friend, it implies that both are friend with each other. 17 | 18 | 19 | ### Representation 20 | 21 | 1. **Adjacency Lists**: Each node is represented as an entry and all the edges are represented as a list emerging from the corresponding node. So if vertex `1` has eadges to 2,3, and 6, the list corresponding to 1 will have 2,3 and 6 as entries. Consider the following graph. 22 | 23 | ``` 24 | 0: 1-->2-->3 25 | 1: 0-->2 26 | 2: 0-->1 27 | 3: 0-->4 28 | 4: 3 29 | ``` 30 | It means there are edges from 0 to 1, 2 and 3; from 1 to 0 and 2 and so on. 31 | 2. **Adjacency Matrix**: The graph is represented as a matrix of size `|V| x |V|` and an entry 1 in cell `(i,j)` implies that there is an edge from i to j. 0 represents no edge. 32 | The mtrix for the above graph: 33 | 34 | ``` 35 | 0 1 2 3 4 36 | 37 | 0 0 1 1 1 0 38 | 1 1 0 1 0 0 39 | 2 1 1 0 0 0 40 | 3 1 0 0 0 1 41 | 4 0 0 0 1 0 42 | ``` -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.hashmap.hashing; 2 | /* 3 | * this is algo which implies common mathematical set theory concept 4 | * called intersection in which result is common values of both the sets 5 | * here metaphor of sets is HashMap 6 | 7 | 8 | Test Case: 9 | Scanner scn=new Scanner(System.in); 10 | int len =scn.nextInt(); 11 | int arr[]=new int[len]; 12 | int arr2[]=new int[len]; 13 | 14 | for(int i=0;i<2*len;i++) { 15 | 16 | if(i=len) { 19 | arr2[i-len]=scn.nextInt(); 20 | } 21 | } 22 | System.out.println(Main(arr,arr2)); 23 | 24 | 25 | 26 | */ 27 | 28 | import java.util.ArrayList; 29 | import java.util.HashMap; 30 | import java.util.Map; 31 | import java.util.Scanner; 32 | import java.util.Set; 33 | 34 | public class Intersection { 35 | 36 | public static ArrayList Main(int arr[],int arr2[]) { 37 | HashMap hmap=new HashMap<>(); 38 | HashMap hmap2=new HashMap<>(); 39 | for(int i=0;i res=new ArrayList<>(); 48 | for(int i=0;i0) { 50 | int val=hmap.get(arr2[i]); 51 | hmap.put(arr2[i],val-1); 52 | res.add(arr2[i]); 53 | } 54 | 55 | } 56 | return res; 57 | } 58 | public Intersection() { 59 | 60 | } 61 | 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.hashmap.hashing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | 9 | int choice, key; 10 | 11 | HashMap h = new HashMap(7); 12 | Scanner In = new Scanner(System.in); 13 | 14 | while (true) { 15 | System.out.println("Enter your Choice :"); 16 | System.out.println("1. Add Key"); 17 | System.out.println("2. Delete Key"); 18 | System.out.println("3. Print Table"); 19 | System.out.println("4. Exit"); 20 | 21 | choice = In.nextInt(); 22 | 23 | switch (choice) { 24 | case 1: { 25 | System.out.println("Enter the Key: "); 26 | key = In.nextInt(); 27 | h.insertHash(key); 28 | break; 29 | } 30 | case 2: { 31 | System.out.println("Enter the Key delete: "); 32 | key = In.nextInt(); 33 | h.deleteHash(key); 34 | break; 35 | } 36 | case 3: { 37 | System.out.println("Print table"); 38 | h.displayHashtable(); 39 | break; 40 | } 41 | case 4: { 42 | In.close(); 43 | return; 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/heaps/EmptyHeapException.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | /** 4 | * @author Nicolas Renard Exception to be thrown if the getElement method is 5 | * used on an empty heap. 6 | */ 7 | @SuppressWarnings("serial") 8 | public class EmptyHeapException extends Exception { 9 | 10 | public EmptyHeapException(String message) { 11 | super(message); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class GenericHeap >{ 4 | ArrayList data=new ArrayList<>(); 5 | HashMap map=new HashMap<>(); 6 | public void add(T item) { 7 | this.data.add(item); 8 | map.put(item,this.data.size()-1);// 9 | upHeapify(this.data.size()-1); 10 | } 11 | private void upHeapify(int ci) { 12 | int pi=(ci-1)/2; 13 | if(isLarger(this.data.get(ci),this.data.get(pi))>0) { 14 | swap(pi,ci); 15 | upHeapify(pi); 16 | } 17 | } 18 | public void display() { 19 | System.out.println(this.data); 20 | } 21 | public int size() { 22 | return this.data.size(); 23 | } 24 | public boolean isEmpty() { 25 | return this.size()==0; 26 | } 27 | public T remove() { 28 | this.swap(0,this.size()-1); 29 | T rv=this.data.remove(this.size()-1); 30 | downHeapify(0); 31 | map.remove(rv); 32 | return rv; 33 | } 34 | private void downHeapify(int pi) { 35 | int lci=2*pi+1; 36 | int rci=2*pi+2; 37 | int mini=pi; 38 | if(lci0) { 39 | mini=lci; 40 | } 41 | if(rci0) { 42 | mini=rci; 43 | } 44 | if(mini!=pi) { 45 | this.swap(pi,mini); 46 | downHeapify(mini); 47 | } 48 | } 49 | public T get() { 50 | return this.data.get(0); 51 | } 52 | //t has higher property then return +ve 53 | private int isLarger(T t,T o) { 54 | return t.compareTo(o); 55 | } 56 | private void swap(int i,int j) { 57 | T ith=this.data.get(i); 58 | T jth=this.data.get(j); 59 | this.data.set(i,jth); 60 | this.data.set(j,ith); 61 | map.put(ith,j); 62 | map.put(jth,i); 63 | } 64 | public void updatePriority(T item) { 65 | int index=map.get(item); 66 | //because we enter lesser value then old vale 67 | upHeapify(index); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/heaps/Heap.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | /** 4 | * Interface common to heap data structures.
5 | * 6 | *

7 | * Heaps are tree-like data structures that allow storing elements in a specific 8 | * way. Each node corresponds to an element and has one parent node (except for 9 | * the root) and at most two children nodes. Every element contains a key, and 10 | * those keys indicate how the tree shall be built. For instance, for a 11 | * min-heap, the key of a node shall be greater than or equal to its parent's 12 | * and lower than or equal to its children's (the opposite rule applies to a 13 | * max-heap). 14 | * 15 | *

16 | * All heap-related operations (inserting or deleting an element, extracting the 17 | * min or max) are performed in O(log n) time. 18 | * 19 | * @author Nicolas Renard 20 | */ 21 | public interface Heap { 22 | 23 | /** 24 | * @return the top element in the heap, the one with lowest key for min-heap 25 | * or with the highest key for max-heap 26 | * @throws EmptyHeapException if heap is empty 27 | */ 28 | HeapElement getElement() throws EmptyHeapException; 29 | 30 | /** 31 | * Inserts an element in the heap. Adds it to then end and toggle it until 32 | * it finds its right position. 33 | * 34 | * @param element an instance of the HeapElement class. 35 | */ 36 | void insertElement(HeapElement element); 37 | 38 | /** 39 | * Delete an element in the heap. 40 | * 41 | * @param elementIndex int containing the position in the heap of the 42 | * element to be deleted. 43 | */ 44 | void deleteElement(int elementIndex); 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class CountSinglyLinkedListRecursion extends SinglyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion(); 7 | for (int i = 1; i <= 5; ++i) { 8 | list.insert(i); 9 | } 10 | assert list.count() == 5; 11 | } 12 | 13 | /** 14 | * Calculate the count of the list manually using recursion. 15 | * 16 | * @param head head of the list. 17 | * @return count of the list. 18 | */ 19 | private int countRecursion(Node head) { 20 | return head == null ? 0 : 1 + countRecursion(head.next); 21 | } 22 | 23 | /** 24 | * Returns the count of the list. 25 | */ 26 | @Override 27 | public int count() { 28 | return countRecursion(getHead()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class MergeSortedSinglyLinkedList extends SinglyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | SinglyLinkedList listA = new SinglyLinkedList(); 7 | SinglyLinkedList listB = new SinglyLinkedList(); 8 | 9 | for (int i = 2; i <= 10; i += 2) { 10 | listA.insert(i); 11 | listB.insert(i - 1); 12 | } 13 | assert listA.toString().equals("2->4->6->8->10"); 14 | assert listB.toString().equals("1->3->5->7->9"); 15 | assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10"); 16 | } 17 | 18 | /** 19 | * Merge two sorted SingleLinkedList 20 | * 21 | * @param listA the first sorted list 22 | * @param listB the second sored list 23 | * @return merged sorted list 24 | */ 25 | public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) { 26 | Node headA = listA.getHead(); 27 | Node headB = listB.getHead(); 28 | 29 | int size = listA.size() + listB.size(); 30 | 31 | Node head = new Node(); 32 | Node tail = head; 33 | while (headA != null && headB != null) { 34 | if (headA.value <= headB.value) { 35 | tail.next = headA; 36 | headA = headA.next; 37 | } else { 38 | tail.next = headB; 39 | headB = headB.next; 40 | } 41 | tail = tail.next; 42 | } 43 | if (headA == null) { 44 | tail.next = headB; 45 | } 46 | if (headB == null) { 47 | tail.next = headA; 48 | } 49 | return new SinglyLinkedList(head.next, size); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.PriorityQueue; 6 | 7 | /** 8 | * @author Arun Pandey (https://github.com/pandeyarun709) 9 | */ 10 | public class Merge_K_SortedLinkedlist { 11 | 12 | /** 13 | * This function merge K sorted LinkedList 14 | * 15 | * @param a array of LinkedList 16 | * @param N size of array 17 | * @return node 18 | */ 19 | Node mergeKList(Node[] a, int N) { 20 | // Min Heap 21 | PriorityQueue min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); 22 | 23 | // adding head of all linkedList in min heap 24 | min.addAll(Arrays.asList(a).subList(0, N)); 25 | 26 | // Make new head among smallest heads in K linkedList 27 | Node head = min.poll(); 28 | min.add(head.next); 29 | Node curr = head; 30 | 31 | // merging LinkedList 32 | while (!min.isEmpty()) { 33 | 34 | Node temp = min.poll(); 35 | curr.next = temp; 36 | curr = temp; 37 | 38 | // Add Node in min Heap only if temp.next is not null 39 | if (temp.next != null) { 40 | min.add(temp.next); 41 | } 42 | } 43 | 44 | return head; 45 | } 46 | 47 | private class Node { 48 | 49 | private int data; 50 | private Node next; 51 | 52 | public Node(int d) { 53 | this.data = d; 54 | next = null; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/README.md: -------------------------------------------------------------------------------- 1 | ## Linked List 2 | ### Description 3 | 4 | LinkedList is a data structure in which data is stored in a linear manner. It usually contains a data field and a link to the memory location of the next mode. 5 | 6 | ### Structure 7 | 8 | ``` 9 | class LinkedList{ 10 | E value; 11 | LinkedList next; 12 | } 13 | ``` 14 | 15 | The `next` variable points to the next node in the data structure and value stores the data. Any number of nodes can be linked in this manner. The structure will be: 16 | 17 | 18 | ### Properties 19 | 1. Linked list does not provide indexing like an array. For accessing a node at position `p` , θ(p) nodes need to be accessed. 20 | 2. Main advantage of linked list is addition and removal of nodes near the end and beginning of lists. It can be done just by updating the link (O(1) time) 21 | 3. Unlike an array, its size is not predefined. So any number of nodes can be appended. 22 | 23 | ### File descriptions: 24 | 25 | 1. `CircleLinkedList.java` : A circular linked list where next pointer of last node points to first nide of linked list. 26 | 2. `SinglyLinkedList.java` : The classic case of single links. 27 | 3. `CountSinglyLinkedListRecursion.java`: Recursively counts the size of a list. 28 | 4. `CreateAndDetectLoop.java` : Create and detect a loop in a linked list. 29 | 5. `DoublyLinkedList.java` : A modification of singly linked list which has a `prev` pointer to point to the previous node. 30 | 6. `Merge_K_SortedLinkedlist.java` : Merges K sorted linked list with mergesort (mergesort is also the most efficient sorting algorithm for linked list). 31 | 7. `RandomNode.java` : Selects a random node from given linked list and diplays it. -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/RemoveDuplicateNodes.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class RemoveDuplicateNodes { 4 | 5 | public Node deleteDuplicates(Node head) { 6 | // sentinel 7 | Node sentinel = new Node(0, head); 8 | 9 | // predecessor = the last node 10 | // before the sublist of duplicates 11 | Node pred = sentinel; 12 | 13 | while (head != null) { 14 | // if it's a beginning of duplicates sublist 15 | // skip all duplicates 16 | if (head.next != null && head.value == head.next.value) { 17 | // move till the end of duplicates sublist 18 | while (head.next != null && head.value == head.next.value) { 19 | head = head.next; 20 | } 21 | // skip all duplicates 22 | pred.next = head.next; 23 | // otherwise, move predecessor 24 | } else { 25 | pred = pred.next; 26 | } 27 | 28 | // move forward 29 | head = head.next; 30 | } 31 | return sentinel.next; 32 | } 33 | 34 | public void print(Node head) { 35 | Node temp = head; 36 | while (temp != null && temp.next != null) { 37 | System.out.print(temp.value + "->"); 38 | temp = temp.next; 39 | } 40 | if (temp != null) { 41 | System.out.print(temp.value); 42 | } 43 | } 44 | 45 | public static void main(String arg[]) { 46 | RemoveDuplicateNodes instance = new RemoveDuplicateNodes(); 47 | Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4))))); 48 | head = instance.deleteDuplicates(head); 49 | instance.print(head); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class SearchSinglyLinkedListRecursion extends SinglyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion(); 7 | for (int i = 1; i <= 10; ++i) { 8 | list.insert(i); 9 | } 10 | 11 | for (int i = 1; i <= 10; ++i) { 12 | assert list.search(i); 13 | } 14 | assert !list.search(-1) && !list.search(100); 15 | } 16 | 17 | /** 18 | * Test if the value key is present in the list using recursion. 19 | * 20 | * @param node the head node. 21 | * @param key the value to be searched. 22 | * @return {@code true} if key is present in the list, otherwise 23 | * {@code false}. 24 | */ 25 | private boolean searchRecursion(Node node, int key) { 26 | return node != null && (node.value == key || searchRecursion(node.next, key)); 27 | } 28 | 29 | @Override 30 | public boolean search(int key) { 31 | return searchRecursion(getHead(), key); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/queues/README.md: -------------------------------------------------------------------------------- 1 | # Queue 2 | - The Queue interface is present in the `java.util` package. 3 | - It is an ordered list of objects that follows the **FIFO** (First-In-First-Out) principle. 4 | 5 | ## Characteristics of a Queue 6 | - The Queue is used to insert elements at the end of the queue and removes elements from the beginning of the queue. 7 | - It supports all methods of Collection interface including insertion, deletion etc. 8 | - LinkedList, ArrayBlockingQueue and PriorityQueue are the most commonly used implementations. 9 | 10 | ## Declaration 11 | 12 | `Queue queue = new PriorityQueue ();` 13 | 14 | ## Important operations 15 | 16 | | Operations | Description | 17 | | ----------- | ----------- | 18 | |Enqueue|Adds an item to the queue| 19 | |Dequeue|Removes an item from the queue| 20 | |Front|Gets the front item from the queue| 21 | |Rear|Gets the last item from the queue| 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.stacks; 2 | 3 | import java.util.Stack; 4 | 5 | public class DecimalToAnyUsingStack { 6 | 7 | public static void main(String[] args) { 8 | assert convert(0, 2).equals("0"); 9 | assert convert(30, 2).equals("11110"); 10 | assert convert(30, 8).equals("36"); 11 | assert convert(30, 10).equals("30"); 12 | assert convert(30, 16).equals("1E"); 13 | } 14 | 15 | /** 16 | * Convert decimal number to another radix 17 | * 18 | * @param number the number to be converted 19 | * @param radix the radix 20 | * @return another radix 21 | * @throws ArithmeticException if number or radius is 22 | * invalid 23 | */ 24 | private static String convert(int number, int radix) { 25 | if (radix < 2 || radix > 16) { 26 | throw new ArithmeticException( 27 | String.format("Invalid input -> number:%d,radius:%d", number, radix)); 28 | } 29 | char[] tables = { 30 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 31 | }; 32 | Stack bits = new Stack<>(); 33 | do { 34 | bits.push(tables[number % radix]); 35 | number = number / radix; 36 | } while (number != 0); 37 | 38 | StringBuilder result = new StringBuilder(); 39 | while (!bits.isEmpty()) { 40 | result.append(bits.pop()); 41 | } 42 | return result.toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.stacks; 2 | 3 | // 1. You are given a string exp representing an expression. 4 | // 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other. 5 | // 3. But, some of the pair of brackets maybe extra/needless. 6 | // 4. You are required to print true if you detect extra brackets and false otherwise. 7 | // e.g.' 8 | // ((a + b) + (c + d)) -> false 9 | // (a + b) + ((c + d)) -> true 10 | import java.util.*; 11 | 12 | public class DuplicateBrackets { 13 | 14 | public static boolean check(String str) { 15 | Stack st = new Stack<>(); 16 | 17 | for (int i = 0; i < str.length(); i++) { 18 | char ch = str.charAt(i); 19 | if (ch == ')') { 20 | if (st.peek() == '(') { 21 | return true; 22 | } else { 23 | while (st.size() > 0 && st.peek() != '(') { 24 | st.pop(); 25 | } 26 | st.pop(); 27 | } 28 | 29 | } else { 30 | st.push(ch); 31 | } 32 | // System.out.println(st); 33 | } 34 | return false; 35 | } 36 | 37 | public static void main(String[] args) throws Exception { 38 | Scanner sc = new Scanner(System.in); 39 | String str = sc.nextLine(); 40 | System.out.println(check(str)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/README.md: -------------------------------------------------------------------------------- 1 | # STACK 2 | 3 | Stack is an ADT (abstract data type) that acts like a list of objects but there is a difference. 4 | 5 | Stack works on the principle of _LIFO_ (Last In First Out), it means that the last item added to the stack will be the first item to be removed. 6 | 7 | Stack is based on two methods (functions)- 8 | 9 | ## push(element) 10 | 11 | It adds "element" to the top of the stack. 12 | 13 | For example: If we have `1, 3, 5` in stack, and we call push(9), 14 | 15 | `9` will be added to last index of stack -> `1, 3, 5 , 9`. 16 | 17 | ## peek() or top() 18 | 19 | It returns element at the top of the stack. 20 | 21 | For example: If we have `1, 3, 5` in stack, and we call peek(), 22 | 23 | `5` will be returned (without removing it from the stack). 24 | 25 | ## pop() 26 | 27 | It removes the last element (i.e. top of stack) from stack. 28 | 29 | For example: If we have `1, 3, 5 , 9` in stack, and we call pop(), 30 | 31 | the function will return `9` and the stack will change to `1, 3, 5`. 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | import com.thealgorithms.datastructures.trees.BinaryTree.Node; 4 | 5 | /** 6 | * Given a sorted array. Create a balanced binary search tree from it. 7 | * 8 | * Steps: 1. Find the middle element of array. This will act as root 2. Use the 9 | * left half recursively to create left subtree 3. Use the right half 10 | * recursively to create right subtree 11 | */ 12 | public class CreateBSTFromSortedArray { 13 | 14 | public static void main(String[] args) { 15 | test(new int[]{}); 16 | test(new int[]{1, 2, 3}); 17 | test(new int[]{1, 2, 3, 4, 5}); 18 | test(new int[]{1, 2, 3, 4, 5, 6, 7}); 19 | } 20 | 21 | private static void test(int[] array) { 22 | BinaryTree root = new BinaryTree(createBst(array, 0, array.length - 1)); 23 | System.out.println("\n\nPreorder Traversal: "); 24 | root.preOrder(root.getRoot()); 25 | System.out.println("\nInorder Traversal: "); 26 | root.inOrder(root.getRoot()); 27 | System.out.println("\nPostOrder Traversal: "); 28 | root.postOrder(root.getRoot()); 29 | } 30 | 31 | private static Node createBst(int[] array, int start, int end) { 32 | // No element left. 33 | if (start > end) { 34 | return null; 35 | } 36 | int mid = start + (end - start) / 2; 37 | 38 | // middle element will be the root 39 | Node root = new Node(array[mid]); 40 | root.left = createBst(array, start, mid - 1); 41 | root.right = createBst(array, mid + 1, end); 42 | return root; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | public class FenwickTree { 4 | 5 | private int n; 6 | private int fen_t[]; 7 | 8 | /* Constructor which takes the size of the array as a parameter */ 9 | public FenwickTree(int n) { 10 | this.n = n; 11 | this.fen_t = new int[n + 1]; 12 | } 13 | 14 | /* A function which will add the element val at index i*/ 15 | public void update(int i, int val) { 16 | // As index starts from 0, increment the index by 1 17 | i += 1; 18 | while (i <= n) { 19 | fen_t[i] += val; 20 | i += i & (-i); 21 | } 22 | } 23 | 24 | /* A function which will return the cumulative sum from index 1 to index i*/ 25 | public int query(int i) { 26 | // As index starts from 0, increment the index by 1 27 | i += 1; 28 | int cumSum = 0; 29 | while (i > 0) { 30 | cumSum += fen_t[i]; 31 | i -= i & (-i); 32 | } 33 | return cumSum; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | public class LevelOrderTraversal { 4 | 5 | class Node { 6 | 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int item) { 11 | data = item; 12 | left = right = null; 13 | } 14 | } 15 | 16 | // Root of the Binary Tree 17 | Node root; 18 | 19 | public LevelOrderTraversal(Node root) { 20 | this.root = root; 21 | } 22 | 23 | /* function to print level order traversal of tree*/ 24 | void printLevelOrder() { 25 | int h = height(root); 26 | int i; 27 | for (i = 1; i <= h; i++) { 28 | printGivenLevel(root, i); 29 | } 30 | } 31 | 32 | /* Compute the "height" of a tree -- the number of 33 | nodes along the longest path from the root node 34 | down to the farthest leaf node.*/ 35 | int height(Node root) { 36 | if (root == null) { 37 | return 0; 38 | } else { 39 | /** 40 | * Return the height of larger subtree 41 | */ 42 | return Math.max(height(root.left), height(root.right)) + 1; 43 | } 44 | } 45 | 46 | /* Print nodes at the given level */ 47 | void printGivenLevel(Node root, int level) { 48 | if (root == null) { 49 | return; 50 | } 51 | if (level == 1) { 52 | System.out.print(root.data + " "); 53 | } else if (level > 1) { 54 | printGivenLevel(root.left, level - 1); 55 | printGivenLevel(root.right, level - 1); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalQueue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /* Class to print Level Order Traversal */ 7 | public class LevelOrderTraversalQueue { 8 | 9 | /* Class to represent Tree node */ 10 | class Node { 11 | 12 | int data; 13 | Node left, right; 14 | 15 | public Node(int item) { 16 | data = item; 17 | left = null; 18 | right = null; 19 | } 20 | } 21 | 22 | /* Given a binary tree. Print its nodes in level order 23 | using array for implementing queue */ 24 | void printLevelOrder(Node root) { 25 | Queue queue = new LinkedList(); 26 | queue.add(root); 27 | while (!queue.isEmpty()) { 28 | 29 | /* poll() removes the present head. 30 | For more information on poll() visit 31 | http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */ 32 | Node tempNode = queue.poll(); 33 | System.out.print(tempNode.data + " "); 34 | 35 | /*Enqueue left child */ 36 | if (tempNode.left != null) { 37 | queue.add(tempNode.left); 38 | } 39 | 40 | /*Enqueue right child */ 41 | if (tempNode.right != null) { 42 | queue.add(tempNode.right); 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/README.md: -------------------------------------------------------------------------------- 1 | ## Tree 2 | ### Description 3 | 4 | Tree is a data structure where the data is organized in a hierarchial structure. There should be one root node (which does not have any parent) and all subsequent nodes are represented as children of the root node and its children. If a node has at least one child, it is called `internal` node and nodes with no children are called `leaf` nodes. 5 | 6 | ### Basic Structure 7 | 8 | ``` 9 | class Tree{ 10 | E value; 11 | Tree left; 12 | Tree right; 13 | } 14 | ``` 15 | 16 | This basic structure is for a binary tree where each internal tree has at least one and at most two children. `left` and `right` represent the two children and `value` is the placeholder for data. 17 | 18 | 19 | ### Properties 20 | 1. Tree data structure gives the facility to organize data in a hierarchial structure 21 | 2. Tree nodes can be inserted in a sorted order which can be used for searching and inserting data in O(logN) time where N is the number of nodes. 22 | 23 | ### Types of Trees 24 | 1. **Binary Search Tree:** A binary tree where the elements are inserted in asorted order. Here the searching can be done in O(logN) time in (depending on the structure) 25 | 2. **AVL Tree and Red-Black Tree:** Binary search trees where the height is balanced. Here, searching is guaranteed to be in O(logN) time. 26 | 3. **Traversal algorithms:**
27 | a. **BFS:** Breadth-first-search where all the children at each level are traversed at once.
28 | b. **DFS:** Depth-first-search where the first discovered child is traversed first. 29 | 4. **MultiWay Search Tree:** Tree in sorted order, but more than two children in each internal node. 30 | 5. **Trie:** A character based multiway search tree where words can be retrieved based on their prefix. Useful for implementing prefix based search algorithm. -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | public class ValidBSTOrNot { 4 | 5 | class Node { 6 | 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int item) { 11 | data = item; 12 | left = right = null; 13 | } 14 | } 15 | 16 | // Root of the Binary Tree 17 | 18 | /* can give min and max value according to your code or 19 | can write a function to find min and max value of tree. */ 20 | 21 | /* returns true if given search tree is binary 22 | search tree (efficient version) */ 23 | boolean isBST(Node root) { 24 | return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); 25 | } 26 | 27 | /* Returns true if the given tree is a BST and its 28 | values are >= min and <= max. */ 29 | boolean isBSTUtil(Node node, int min, int max) { 30 | /* an empty tree is BST */ 31 | if (node == null) { 32 | return true; 33 | } 34 | 35 | /* false if this node violates the min/max constraints */ 36 | if (node.data < min || node.data > max) { 37 | return false; 38 | } 39 | 40 | /* otherwise check the subtrees recursively 41 | tightening the min/max constraints */ 42 | // Allow only distinct values 43 | return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/nodes/Node.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.nodes; 2 | 3 | /** 4 | * Base class for any node implementation which contains a generic type 5 | * variable. 6 | * 7 | * All known subclasses: {@link TreeNode}, {@link SimpleNode}. 8 | * 9 | * @param The type of the data held in the Node. 10 | * 11 | * @author aitorfi 12 | */ 13 | public abstract class Node { 14 | 15 | /** 16 | * Generic type data stored in the Node. 17 | */ 18 | private E data; 19 | 20 | /** 21 | * Empty constructor. 22 | */ 23 | public Node() { 24 | } 25 | 26 | /** 27 | * Initializes the Nodes' data. 28 | * 29 | * @param data Value to which data will be initialized. 30 | */ 31 | public Node(E data) { 32 | this.data = data; 33 | } 34 | 35 | public E getData() { 36 | return data; 37 | } 38 | 39 | public void setData(E data) { 40 | this.data = data; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.nodes; 2 | 3 | /** 4 | * Simple Node implementation that holds a reference to the next Node. 5 | * 6 | * @param The type of the data held in the Node. 7 | * 8 | * @author aitorfi 9 | */ 10 | public class SimpleNode extends Node { 11 | 12 | /** 13 | * Reference to the next Node. 14 | */ 15 | private SimpleNode nextNode; 16 | 17 | /** 18 | * Empty contructor. 19 | */ 20 | public SimpleNode() { 21 | super(); 22 | } 23 | 24 | /** 25 | * Initializes the Nodes' data. 26 | * 27 | * @param data Value to which data will be initialized. 28 | * @see Node#Node(Object) 29 | */ 30 | public SimpleNode(E data) { 31 | super(data); 32 | } 33 | 34 | /** 35 | * Initializes the Nodes' data and next node reference. 36 | * 37 | * @param data Value to which data will be initialized. 38 | * @param nextNode Value to which the next node reference will be set. 39 | */ 40 | public SimpleNode(E data, SimpleNode nextNode) { 41 | super(data); 42 | this.nextNode = nextNode; 43 | } 44 | 45 | /** 46 | * @return True if there is a next node, otherwise false. 47 | */ 48 | public boolean hasNext() { 49 | return (nextNode != null); 50 | } 51 | 52 | public SimpleNode getNextNode() { 53 | return nextNode; 54 | } 55 | 56 | public void setNextNode(SimpleNode nextNode) { 57 | this.nextNode = nextNode; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.searches; 2 | 3 | /** 4 | * The common interface of most searching algorithms 5 | * 6 | * @author Podshivalov Nikita (https://github.com/nikitap492) 7 | */ 8 | public interface SearchAlgorithm { 9 | 10 | /** 11 | * @param key is an element which should be found 12 | * @param array is an array where the element should be found 13 | * @param Comparable type 14 | * @return first found index of the element 15 | */ 16 | > int find(T array[], T key); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.divideandconquer; 2 | 3 | public class BinaryExponentiation { 4 | 5 | public static void main(String args[]) { 6 | System.out.println(calculatePower(2, 30)); 7 | } 8 | 9 | // Function to calculate x^y 10 | // Time Complexity: O(logn) 11 | public static long calculatePower(long x, long y) { 12 | if (y == 0) { 13 | return 1; 14 | } 15 | long val = calculatePower(x, y / 2); 16 | val *= val; 17 | if (y % 2 == 1) { 18 | val *= x; 19 | } 20 | return val; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /* A Naive recursive implementation 4 | of 0-1 Knapsack problem */ 5 | public class BruteForceKnapsack { 6 | 7 | // A utility function that returns 8 | // maximum of two integers 9 | static int max(int a, int b) { 10 | return (a > b) ? a : b; 11 | } 12 | 13 | // Returns the maximum value that 14 | // can be put in a knapsack of 15 | // capacity W 16 | static int knapSack(int W, int wt[], int val[], int n) { 17 | // Base Case 18 | if (n == 0 || W == 0) { 19 | return 0; 20 | } 21 | 22 | // If weight of the nth item is 23 | // more than Knapsack capacity W, 24 | // then this item cannot be included 25 | // in the optimal solution 26 | if (wt[n - 1] > W) { 27 | return knapSack(W, wt, val, n - 1); 28 | } // Return the maximum of two cases: 29 | // (1) nth item included 30 | // (2) not included 31 | else { 32 | return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)); 33 | } 34 | } 35 | 36 | // Driver code 37 | public static void main(String args[]) { 38 | int val[] = new int[]{60, 100, 120}; 39 | int wt[] = new int[]{10, 20, 30}; 40 | int W = 50; 41 | int n = val.length; 42 | System.out.println(knapSack(W, wt, val, n)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | // A Dynamic Programming based solution 4 | // for 0-1 Knapsack problem 5 | public class DyanamicProgrammingKnapsack { 6 | 7 | static int max(int a, int b) { 8 | return (a > b) ? a : b; 9 | } 10 | 11 | // Returns the maximum value that can 12 | // be put in a knapsack of capacity W 13 | static int knapSack(int W, int wt[], int val[], int n) { 14 | int i, w; 15 | int K[][] = new int[n + 1][W + 1]; 16 | 17 | // Build table K[][] in bottom up manner 18 | for (i = 0; i <= n; i++) { 19 | for (w = 0; w <= W; w++) { 20 | if (i == 0 || w == 0) { 21 | K[i][w] = 0; 22 | } else if (wt[i - 1] <= w) { 23 | K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); 24 | } else { 25 | K[i][w] = K[i - 1][w]; 26 | } 27 | } 28 | } 29 | 30 | return K[n][W]; 31 | } 32 | 33 | // Driver code 34 | public static void main(String args[]) { 35 | int val[] = new int[]{60, 100, 120}; 36 | int wt[] = new int[]{10, 20, 30}; 37 | int W = 50; 38 | int n = val.length; 39 | System.out.println(knapSack(W, wt, val, n)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * DynamicProgramming solution for the Egg Dropping Puzzle 5 | */ 6 | public class EggDropping { 7 | 8 | // min trials with n eggs and m floors 9 | private static int minTrials(int n, int m) { 10 | 11 | int[][] eggFloor = new int[n + 1][m + 1]; 12 | int result, x; 13 | 14 | for (int i = 1; i <= n; i++) { 15 | eggFloor[i][0] = 0; // Zero trial for zero floor. 16 | eggFloor[i][1] = 1; // One trial for one floor 17 | } 18 | 19 | // j trials for only 1 egg 20 | for (int j = 1; j <= m; j++) { 21 | eggFloor[1][j] = j; 22 | } 23 | 24 | // Using bottom-up approach in DP 25 | for (int i = 2; i <= n; i++) { 26 | for (int j = 2; j <= m; j++) { 27 | eggFloor[i][j] = Integer.MAX_VALUE; 28 | for (x = 1; x <= j; x++) { 29 | result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); 30 | 31 | // choose min of all values for particular x 32 | if (result < eggFloor[i][j]) { 33 | eggFloor[i][j] = result; 34 | } 35 | } 36 | } 37 | } 38 | 39 | return eggFloor[n][m]; 40 | } 41 | 42 | public static void main(String args[]) { 43 | int n = 2, m = 4; 44 | // result outputs min no. of trials in worst case for n eggs and m floors 45 | int result = minTrials(n, m); 46 | System.out.println(result); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Program to implement Kadane’s Algorithm to calculate maximum contiguous 7 | * subarray sum of an array Time Complexity: O(n) 8 | * 9 | * @author Nishita Aggarwal 10 | */ 11 | public class KadaneAlgorithm { 12 | 13 | /** 14 | * This method implements Kadane's Algorithm 15 | * 16 | * @param arr The input array 17 | * @return The maximum contiguous subarray sum of the array 18 | */ 19 | static int largestContiguousSum(int arr[]) { 20 | int i, len = arr.length, cursum = 0, maxsum = Integer.MIN_VALUE; 21 | if (len == 0) // empty array 22 | { 23 | return 0; 24 | } 25 | for (i = 0; i < len; i++) { 26 | cursum += arr[i]; 27 | if (cursum > maxsum) { 28 | maxsum = cursum; 29 | } 30 | if (cursum <= 0) { 31 | cursum = 0; 32 | } 33 | } 34 | return maxsum; 35 | } 36 | 37 | /** 38 | * Main method 39 | * 40 | * @param args Command line arguments 41 | */ 42 | public static void main(String[] args) { 43 | Scanner sc = new Scanner(System.in); 44 | int n, arr[], i; 45 | n = sc.nextInt(); 46 | arr = new int[n]; 47 | for (i = 0; i < n; i++) { 48 | arr[i] = sc.nextInt(); 49 | } 50 | int maxContSum = largestContiguousSum(arr); 51 | System.out.println(maxContSum); 52 | sc.close(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * A DynamicProgramming based solution for 0-1 Knapsack problem 5 | */ 6 | public class Knapsack { 7 | 8 | private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { 9 | if (wt == null || val == null) { 10 | throw new IllegalArgumentException(); 11 | } 12 | int i, w; 13 | int rv[][] = new int[n + 1][W + 1]; // rv means return value 14 | 15 | // Build table rv[][] in bottom up manner 16 | for (i = 0; i <= n; i++) { 17 | for (w = 0; w <= W; w++) { 18 | if (i == 0 || w == 0) { 19 | rv[i][w] = 0; 20 | } else if (wt[i - 1] <= w) { 21 | rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); 22 | } else { 23 | rv[i][w] = rv[i - 1][w]; 24 | } 25 | } 26 | } 27 | 28 | return rv[n][W]; 29 | } 30 | 31 | // Driver program to test above function 32 | public static void main(String args[]) { 33 | int val[] = new int[]{50, 100, 130}; 34 | int wt[] = new int[]{10, 20, 40}; 35 | int W = 50; 36 | System.out.println(knapSack(W, wt, val, val.length)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /* 4 | * Algorithm explanation https://leetcode.com/problems/longest-palindromic-substring/ 5 | */ 6 | public class LongestPalindromicSubstring { 7 | 8 | public static void main(String[] args) { 9 | String a = "babad"; 10 | String b = "cbbd"; 11 | 12 | String aLPS = LPS(a); 13 | String bLPS = LPS(b); 14 | 15 | System.out.println(a + " => " + aLPS); 16 | System.out.println(b + " => " + bLPS); 17 | } 18 | 19 | private static String LPS(String input) { 20 | if (input == null || input.length() == 0) { 21 | return input; 22 | } 23 | boolean arr[][] = new boolean[input.length()][input.length()]; 24 | int start = 0, end = 0; 25 | for (int g = 0; g < input.length(); g++) { 26 | for (int i = 0, j = g; j < input.length(); i++, j++) { 27 | 28 | if (g == 0) { 29 | arr[i][j] = true; 30 | } else if (g == 1) { 31 | if (input.charAt(i) == input.charAt(j)) { 32 | arr[i][j] = true; 33 | } else { 34 | arr[i][j] = false; 35 | } 36 | } else { 37 | 38 | if (input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1]) { 39 | arr[i][j] = true; 40 | } else { 41 | arr[i][j] = false; 42 | } 43 | } 44 | 45 | if (arr[i][j]) { 46 | start = i; 47 | end = j; 48 | } 49 | } 50 | } 51 | return input.substring(start, end + 1); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Given a string containing just the characters '(' and ')', find the length of 7 | * the longest valid (well-formed) parentheses substring. 8 | * 9 | * @author Libin Yang (https://github.com/yanglbme) 10 | * @since 2018/10/5 11 | */ 12 | public class LongestValidParentheses { 13 | 14 | public static int getLongestValidParentheses(String s) { 15 | if (s == null || s.length() < 2) { 16 | return 0; 17 | } 18 | char[] chars = s.toCharArray(); 19 | int n = chars.length; 20 | int[] res = new int[n]; 21 | res[0] = 0; 22 | res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; 23 | 24 | int max = res[1]; 25 | 26 | for (int i = 2; i < n; ++i) { 27 | if (chars[i] == ')') { 28 | if (chars[i - 1] == '(') { 29 | res[i] = res[i - 2] + 2; 30 | } else { 31 | int index = i - res[i - 1] - 1; 32 | if (index >= 0 && chars[index] == '(') { 33 | // ()(()) 34 | res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); 35 | } 36 | } 37 | } 38 | max = Math.max(max, res[i]); 39 | } 40 | 41 | return max; 42 | } 43 | 44 | public static void main(String[] args) { 45 | Scanner sc = new Scanner(System.in); 46 | 47 | while (true) { 48 | String str = sc.nextLine(); 49 | if ("quit".equals(str)) { 50 | break; 51 | } 52 | 53 | System.out.println("Len is: " + getLongestValidParentheses(str)); 54 | } 55 | 56 | sc.close(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | // Matrix-chain Multiplication 4 | // Problem Statement 5 | // we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n, 6 | // matrix Ai has dimension pi−1 ×pi 7 | // , fully parenthesize the product A1A2 ···An in a way that 8 | // minimizes the number of scalar multiplications. 9 | public class MatrixChainRecursiveTopDownMemoisation { 10 | 11 | static int Memoized_Matrix_Chain(int p[]) { 12 | int n = p.length; 13 | int m[][] = new int[n][n]; 14 | for (int i = 0; i < n; i++) { 15 | for (int j = 0; j < n; j++) { 16 | m[i][j] = Integer.MAX_VALUE; 17 | } 18 | } 19 | return Lookup_Chain(m, p, 1, n - 1); 20 | } 21 | 22 | static int Lookup_Chain(int m[][], int p[], int i, int j) { 23 | if (i == j) { 24 | m[i][j] = 0; 25 | return m[i][j]; 26 | } 27 | if (m[i][j] < Integer.MAX_VALUE) { 28 | return m[i][j]; 29 | } else { 30 | for (int k = i; k < j; k++) { 31 | int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j) + (p[i - 1] * p[k] * p[j]); 32 | if (q < m[i][j]) { 33 | m[i][j] = q; 34 | } 35 | } 36 | } 37 | return m[i][j]; 38 | } 39 | 40 | // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively 41 | // output should be Minimum number of multiplications is 38 42 | public static void main(String[] args) { 43 | 44 | int arr[] = {1, 2, 3, 4, 5}; 45 | System.out.println("Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * A DynamicProgramming solution for Rod cutting problem Returns the best 5 | * obtainable price for a rod of length n and price[] as prices of different 6 | * pieces 7 | */ 8 | public class RodCutting { 9 | 10 | private static int cutRod(int[] price, int n) { 11 | int val[] = new int[n + 1]; 12 | val[0] = 0; 13 | 14 | for (int i = 1; i <= n; i++) { 15 | int max_val = Integer.MIN_VALUE; 16 | for (int j = 0; j < i; j++) { 17 | max_val = Math.max(max_val, price[j] + val[i - j - 1]); 18 | } 19 | 20 | val[i] = max_val; 21 | } 22 | 23 | return val[n]; 24 | } 25 | 26 | // main function to test 27 | public static void main(String args[]) { 28 | int[] arr = new int[]{2, 5, 13, 19, 20}; 29 | int result = cutRod(arr, arr.length); 30 | System.out.println("Maximum Obtainable Value is " + result); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | public class SubsetSum { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | int[] arr = new int[]{50, 4, 10, 15, 34}; 10 | assert subsetSum(arr, 64); 11 | /* 4 + 10 + 15 + 34 = 64 */ 12 | assert subsetSum(arr, 99); 13 | /* 50 + 15 + 34 = 99 */ 14 | assert !subsetSum(arr, 5); 15 | assert !subsetSum(arr, 66); 16 | } 17 | 18 | /** 19 | * Test if a set of integers contains a subset that sum to a given integer. 20 | * 21 | * @param arr the array contains integers. 22 | * @param sum target sum of subset. 23 | * @return {@code true} if subset exists, otherwise {@code false}. 24 | */ 25 | private static boolean subsetSum(int[] arr, int sum) { 26 | int n = arr.length; 27 | boolean[][] isSum = new boolean[n + 2][sum + 1]; 28 | 29 | isSum[n + 1][0] = true; 30 | for (int i = 1; i <= sum; i++) { 31 | isSum[n + 1][i] = false; 32 | } 33 | 34 | for (int i = n; i > 0; i--) { 35 | isSum[i][0] = true; 36 | for (int j = 1; j <= arr[i - 1] - 1; j++) { 37 | if (j <= sum) { 38 | isSum[i][j] = isSum[i + 1][j]; 39 | } 40 | } 41 | for (int j = arr[i - 1]; j <= sum; j++) { 42 | isSum[i][j] = (isSum[i + 1][j] || isSum[i + 1][j - arr[i - 1]]); 43 | } 44 | } 45 | 46 | return isSum[1][sum]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | public class Sum_Of_Subset { 4 | 5 | public static void main(String[] args) { 6 | 7 | int[] arr = {7, 3, 2, 5, 8}; 8 | int Key = 14; 9 | 10 | if (subsetSum(arr, arr.length - 1, Key)) { 11 | System.out.print("Yes, that sum exists"); 12 | } else { 13 | System.out.print("Nope, that number does not exist"); 14 | } 15 | } 16 | 17 | public static boolean subsetSum(int[] arr, int num, int Key) { 18 | if (Key == 0) { 19 | return true; 20 | } 21 | if (num < 0 || Key < 0) { 22 | return false; 23 | } 24 | 25 | boolean include = subsetSum(arr, num - 1, Key - arr[num]); 26 | boolean exclude = subsetSum(arr, num - 1, Key); 27 | 28 | return include || exclude; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteMax.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * description: 7 | * 8 | *

9 | * absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10 10 | */ 11 | public class AbsoluteMax { 12 | 13 | public static void main(String[] args) { 14 | int[] testnums = {-2, 0, 16}; 15 | assert absMax(testnums) == 16; 16 | 17 | int[] numbers = {3, -10, -2}; 18 | System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers)); 19 | } 20 | 21 | /** 22 | * get the value, return the absolute max value 23 | * 24 | * @param numbers contains elements 25 | * @return the absolute max value 26 | */ 27 | public static int absMax(int[] numbers) { 28 | int absMaxValue = numbers[0]; 29 | for (int i = 1, length = numbers.length; i < length; ++i) { 30 | if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) { 31 | absMaxValue = numbers[i]; 32 | } 33 | } 34 | return absMaxValue; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteMin.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * description: 7 | * 8 | *

9 | * absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2 10 | */ 11 | public class AbsoluteMin { 12 | 13 | public static void main(String[] args) { 14 | int[] testnums = {4, 0, 16}; 15 | assert absMin(testnums) == 0; 16 | 17 | int[] numbers = {3, -10, -2}; 18 | System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers)); 19 | } 20 | 21 | /** 22 | * get the value, returns the absolute min value min 23 | * 24 | * @param numbers contains elements 25 | * @return the absolute min value 26 | */ 27 | public static int absMin(int[] numbers) { 28 | int absMinValue = numbers[0]; 29 | for (int i = 1, length = numbers.length; i < length; ++i) { 30 | if (Math.abs(numbers[i]) < Math.abs(absMinValue)) { 31 | absMinValue = numbers[i]; 32 | } 33 | } 34 | return absMinValue; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class AbsoluteValue { 6 | 7 | public static void main(String[] args) { 8 | Random random = new Random(); 9 | 10 | /* test 1000 random numbers */ 11 | for (int i = 1; i <= 1000; ++i) { 12 | int randomNumber = random.nextInt(); 13 | assert absVal(randomNumber) == Math.abs(randomNumber); 14 | } 15 | } 16 | 17 | /** 18 | * If value is less than zero, make value positive. 19 | * 20 | * @param value a number 21 | * @return the absolute value of a number 22 | */ 23 | public static int absVal(int value) { 24 | return value < 0 ? -value : value; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AliquotSum.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * In number theory, the aliquot sum s(n) of a positive integer n is the sum of 5 | * all proper divisors of n, that is, all divisors of n other than n itself. For 6 | * example, the proper divisors of 15 (that is, the positive divisors of 15 that 7 | * are not equal to 15) are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + 8 | * 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum 9 | */ 10 | public class AliquotSum { 11 | 12 | public static void main(String[] args) { 13 | assert aliquotSum(1) == 0; 14 | assert aliquotSum(6) == 6; 15 | assert aliquotSum(15) == 9; 16 | assert aliquotSum(19) == 1; 17 | } 18 | 19 | /** 20 | * Finds the aliquot sum of an integer number 21 | * 22 | * @param number a positive integer 23 | * @return aliquot sum of given {@code number} 24 | */ 25 | public static int aliquotSum(int number) { 26 | int sum = 0; 27 | for (int i = 1, limit = number / 2; i <= limit; ++i) { 28 | if (number % i == 0) { 29 | sum += i; 30 | } 31 | } 32 | return sum; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Armstrong.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * An Armstrong number is equal to the sum of the cubes of its digits. For 5 | * example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An 6 | * Armstrong number is often called Narcissistic number. 7 | */ 8 | public class Armstrong { 9 | 10 | public static void main(String[] args) { 11 | assert (isArmStrong(0)); 12 | assert (isArmStrong(1)); 13 | assert (isArmStrong(153)); 14 | assert (isArmStrong(1634)); 15 | assert (isArmStrong(371)); 16 | assert (!isArmStrong(200)); 17 | } 18 | 19 | /** 20 | * Checks whether a given number is an armstrong number or not. 21 | * 22 | * @param number number to check 23 | * @return {@code true} if given number is armstrong number, {@code false} 24 | * otherwise 25 | */ 26 | private static boolean isArmStrong(int number) { 27 | int sum = 0; 28 | int temp = number; 29 | int numberOfDigits = 0; 30 | while (temp != 0) { 31 | numberOfDigits++; 32 | temp /= 10; 33 | } 34 | temp = number; 35 | /* copy number again */ 36 | while (number > 0) { 37 | int remainder = number % 10; 38 | int power = 1; 39 | for (int i = 1; i <= numberOfDigits; power *= remainder, ++i) 40 | ; 41 | sum = sum + power; 42 | number /= 10; 43 | } 44 | return sum == temp; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Average.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Calculate average of a list of numbers 5 | */ 6 | public class Average { 7 | 8 | private static final double SMALL_VALUE = 0.00001f; 9 | 10 | public static void main(String[] args) { 11 | assert Math.abs(average(new double[]{3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE; 12 | assert Math.abs(average(new double[]{5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE; 13 | assert Math.abs(average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE; 14 | int[] array = {2, 4, 10}; 15 | assert average(array) == 5; 16 | } 17 | 18 | /** 19 | * Calculate average of a list of numbers 20 | * 21 | * @param numbers array to store numbers 22 | * @return mean of given numbers 23 | */ 24 | public static double average(double[] numbers) { 25 | double sum = 0; 26 | for (double number : numbers) { 27 | sum += number; 28 | } 29 | return sum / numbers.length; 30 | } 31 | 32 | /** 33 | * find average value of int array 34 | * 35 | * @param array the array contains element and the sum does not excess long 36 | * value limit 37 | * @return average value 38 | */ 39 | public static int average(int[] array) { 40 | long sum = 0; 41 | for (int i = 0; i < array.length; ++i) { 42 | sum += array[i]; 43 | } 44 | return (int) (sum / array.length); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/BinaryPow.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class BinaryPow { 4 | 5 | /** 6 | * Calculate a^p using binary exponentiation 7 | * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html) 8 | * 9 | * @param a the base for exponentiation 10 | * @param p the exponent - must be greater than 0 11 | * @return a^p 12 | */ 13 | public static int binPow(int a, int p) { 14 | int res = 1; 15 | while (p > 0) { 16 | if ((p & 1) == 1) { 17 | res = res * a; 18 | } 19 | a = a * a; 20 | p >>>= 1; 21 | } 22 | return res; 23 | } 24 | 25 | /** 26 | * Function for testing binary exponentiation 27 | * 28 | * @param a the base 29 | * @param p the exponent 30 | */ 31 | public static void test(int a, int p) { 32 | int res = binPow(a, p); 33 | assert res == (int) Math.pow(a, p) : "Incorrect Implementation"; 34 | System.out.println(a + "^" + p + ": " + res); 35 | } 36 | 37 | /** 38 | * Main Function to call tests 39 | * 40 | * @param args System Line Arguments 41 | */ 42 | public static void main(String[] args) { 43 | // prints 2^15: 32768 44 | test(2, 15); 45 | 46 | // prints 3^9: 19683 47 | test(3, 9); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/BinomialCoefficient.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Java program for Binomial Cofficients 5 | * Binomial Cofficients: A binomial cofficient C(n,k) gives number ways 6 | * in which k objects can be chosen from n objects. 7 | * Wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient 8 | * 9 | * Author: Akshay Dubey (https://github.com/itsAkshayDubey) 10 | * 11 | * */ 12 | 13 | public class BinomialCoefficient { 14 | 15 | /** 16 | * This method returns the number of ways in which k objects can be chosen from n objects 17 | * 18 | * @param total_objects Total number of objects 19 | * @param no_of_objects Number of objects to be chosen from total_objects 20 | * @return number of ways in which no_of_objects objects can be chosen from total_objects objects 21 | */ 22 | 23 | static int binomialCoefficient(int total_objects, int no_of_objects) { 24 | 25 | //Base Case 26 | if(no_of_objects > total_objects) { 27 | return 0; 28 | } 29 | 30 | //Base Case 31 | if(no_of_objects == 0 || no_of_objects == total_objects) { 32 | return 1; 33 | } 34 | 35 | //Recursive Call 36 | return binomialCoefficient(total_objects - 1, no_of_objects - 1) 37 | + binomialCoefficient(total_objects - 1, no_of_objects); 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println(binomialCoefficient(20,2)); 42 | 43 | //Output: 190 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Ceil.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class Ceil { 6 | 7 | public static void main(String[] args) { 8 | Random random = new Random(); 9 | for (int i = 1; i <= 1000; ++i) { 10 | double randomNumber = random.nextDouble(); 11 | assert ceil(randomNumber) == Math.ceil(randomNumber); 12 | } 13 | } 14 | 15 | /** 16 | * Returns the smallest (closest to negative infinity) 17 | * 18 | * @param number the number 19 | * @return the smallest (closest to negative infinity) of given 20 | * {@code number} 21 | */ 22 | public static double ceil(double number) { 23 | if (number - (int) number == 0) { 24 | return number; 25 | } else if (number - (int) number > 0) { 26 | return (int) (number + 1); 27 | } else { 28 | return (int) number; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Convolution.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Class for linear convolution of two discrete signals 5 | * 6 | * @author Ioannis Karavitsis 7 | * @version 1.0 8 | */ 9 | public class Convolution { 10 | 11 | /** 12 | * Discrete linear convolution function. Both input signals and the output 13 | * signal must start from 0. If you have a signal that has values before 0 14 | * then shift it to start from 0. 15 | * 16 | * @param A The first discrete signal 17 | * @param B The second discrete signal 18 | * @return The convolved signal 19 | */ 20 | public static double[] convolution(double[] A, double[] B) { 21 | double[] convolved = new double[A.length + B.length - 1]; 22 | 23 | /* 24 | The discrete convolution of two signals A and B is defined as: 25 | 26 | A.length 27 | C[i] = Σ (A[k]*B[i-k]) 28 | k=0 29 | 30 | It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= B.length - 1 31 | From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get the conditions below. 32 | */ 33 | for (int i = 0; i < convolved.length; i++) { 34 | convolved[i] = 0; 35 | int k = Math.max(i - B.length + 1, 0); 36 | 37 | while (k < i + 1 && k < A.length) { 38 | convolved[i] += A[k] * B[i - k]; 39 | k++; 40 | } 41 | } 42 | 43 | return convolved; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.*; 4 | 5 | /* 6 | * @author Ojasva Jain 7 | * Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant 8 | */ 9 | public class DeterminantOfMatrix { 10 | 11 | // Determinant calculator 12 | //@return determinant of the input matrix 13 | static int determinant(int a[][], int n) { 14 | int det = 0, sign = 1, p = 0, q = 0; 15 | if (n == 1) { 16 | det = a[0][0]; 17 | } else { 18 | int b[][] = new int[n - 1][n - 1]; 19 | for (int x = 0; x < n; x++) { 20 | p = 0; 21 | q = 0; 22 | for (int i = 1; i < n; i++) { 23 | for (int j = 0; j < n; j++) { 24 | if (j != x) { 25 | b[p][q++] = a[i][j]; 26 | if (q % (n - 1) == 0) { 27 | p++; 28 | q = 0; 29 | } 30 | } 31 | } 32 | } 33 | det = det + a[0][x] * determinant(b, n - 1) * sign; 34 | sign = -sign; 35 | } 36 | } 37 | return det; 38 | } 39 | 40 | //Driver Method 41 | public static void main(String[] args) { 42 | Scanner in = new Scanner(System.in); 43 | //Input Matrix 44 | System.out.println("Enter matrix size (Square matrix only)"); 45 | int n = in.nextInt(); 46 | System.out.println("Enter matrix"); 47 | int a[][] = new int[n][n]; 48 | for (int i = 0; i < n; i++) { 49 | for (int j = 0; j < n; j++) { 50 | a[i][j] = in.nextInt(); 51 | } 52 | } 53 | System.out.println(determinant(a, n)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Factorial.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class Factorial { 4 | 5 | /* Driver Code */ 6 | public static void main(String[] args) { 7 | assert factorial(0) == 1; 8 | assert factorial(1) == 1; 9 | assert factorial(5) == 120; 10 | assert factorial(10) == 3628800; 11 | } 12 | 13 | /** 14 | * Calculate factorial N using iteration 15 | * 16 | * @param n the number 17 | * @return the factorial of {@code n} 18 | */ 19 | public static long factorial(int n) { 20 | if (n < 0) { 21 | throw new IllegalArgumentException("number is negative"); 22 | } 23 | long factorial = 1; 24 | for (int i = 1; i <= n; factorial *= i, ++i) 25 | ; 26 | return factorial; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FactorialRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class FactorialRecursion { 4 | 5 | /* Driver Code */ 6 | public static void main(String[] args) { 7 | assert factorial(0) == 1; 8 | assert factorial(1) == 1; 9 | assert factorial(2) == 2; 10 | assert factorial(3) == 6; 11 | assert factorial(5) == 120; 12 | } 13 | 14 | /** 15 | * Recursive FactorialRecursion Method 16 | * 17 | * @param n The number to factorial 18 | * @return The factorial of the number 19 | */ 20 | public static long factorial(int n) { 21 | if (n < 0) { 22 | throw new IllegalArgumentException("number is negative"); 23 | } 24 | return n == 0 || n == 1 ? 1 : n * factorial(n - 1); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Fibonacci: 0 1 1 2 3 5 8 13 21 ... 5 | */ 6 | public class FibonacciNumber { 7 | 8 | public static void main(String[] args) { 9 | assert isFibonacciNumber(1); 10 | assert isFibonacciNumber(2); 11 | assert isFibonacciNumber(21); 12 | assert !isFibonacciNumber(9); 13 | assert !isFibonacciNumber(10); 14 | } 15 | 16 | /** 17 | * Check if a number is perfect square number 18 | * 19 | * @param number the number to be checked 20 | * @return true if {@code number} is perfect square, otherwise 21 | * false 22 | */ 23 | public static boolean isPerfectSquare(int number) { 24 | int sqrt = (int) Math.sqrt(number); 25 | return sqrt * sqrt == number; 26 | } 27 | 28 | /** 29 | * Check if a number is fibonacci number This is true if and only if at 30 | * least one of 5x^2+4 or 5x^2-4 is a perfect square 31 | * 32 | * @param number the number 33 | * @return true if {@code number} is fibonacci number, otherwise 34 | * false 35 | * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification 36 | */ 37 | public static boolean isFibonacciNumber(int number) { 38 | return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMax.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | public class FindMax { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | Random random = new Random(); 13 | 14 | /* random size */ 15 | int size = random.nextInt(100) + 1; 16 | int[] array = new int[size]; 17 | 18 | /* init array with random numbers */ 19 | for (int i = 0; i < size; i++) { 20 | array[i] = random.nextInt() % 100; 21 | } 22 | 23 | assert Arrays.stream(array).max().getAsInt() == findMax(array); 24 | } 25 | 26 | /** 27 | * find max of array 28 | * 29 | * @param array the array contains element 30 | * @return max value of given array 31 | */ 32 | public static int findMax(int[] array) { 33 | int max = array[0]; 34 | for (int i = 1; i < array.length; ++i) { 35 | if (array[i] > max) { 36 | max = array[i]; 37 | } 38 | } 39 | return max; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMaxRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | public class FindMaxRecursion { 7 | 8 | public static void main(String[] args) { 9 | Random rand = new Random(); 10 | 11 | /* rand size */ 12 | int size = rand.nextInt(100) + 1; 13 | int[] array = new int[size]; 14 | 15 | /* init array with rand numbers */ 16 | for (int i = 0; i < size; i++) { 17 | array[i] = rand.nextInt() % 100; 18 | } 19 | 20 | assert max(array, array.length) == Arrays.stream(array).max().getAsInt(); 21 | assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt(); 22 | } 23 | 24 | /** 25 | * Get max of array using divide and conquer algorithm 26 | * 27 | * @param array contains elements 28 | * @param low the index of the first element 29 | * @param high the index of the last element 30 | * @return max of {@code array} 31 | */ 32 | public static int max(int[] array, int low, int high) { 33 | if (low == high) { 34 | return array[low]; // or array[high] 35 | } 36 | 37 | int mid = (low + high) >>> 1; 38 | 39 | int leftMax = max(array, low, mid); // get max in [low, mid] 40 | int rightMax = max(array, mid + 1, high); // get max in [mid+1, high] 41 | 42 | return Math.max(leftMax, rightMax); 43 | } 44 | 45 | /** 46 | * Get max of array using recursion algorithm 47 | * 48 | * @param array contains elements 49 | * @param len length of given array 50 | * @return max value of {@code array} 51 | */ 52 | public static int max(int[] array, int len) { 53 | return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMin.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | public class FindMin { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | Random random = new Random(); 13 | 14 | /* random size */ 15 | int size = random.nextInt(100) + 1; 16 | int[] array = new int[size]; 17 | 18 | /* init array with random numbers */ 19 | for (int i = 0; i < size; i++) { 20 | array[i] = random.nextInt() % 100; 21 | } 22 | 23 | assert Arrays.stream(array).min().getAsInt() == findMin(array); 24 | } 25 | 26 | /** 27 | * Find the minimum number of an array of numbers. 28 | * 29 | * @param array the array contains element 30 | * @return min value 31 | */ 32 | public static int findMin(int[] array) { 33 | int min = array[0]; 34 | for (int i = 1; i < array.length; ++i) { 35 | if (array[i] < min) { 36 | min = array[i]; 37 | } 38 | } 39 | return min; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMinRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | public class FindMinRecursion { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | Random rand = new Random(); 13 | 14 | /* rand size */ 15 | int size = rand.nextInt(100) + 1; 16 | int[] array = new int[size]; 17 | 18 | /* init array with rand numbers */ 19 | for (int i = 0; i < size; i++) { 20 | array[i] = rand.nextInt() % 100; 21 | } 22 | 23 | assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt(); 24 | assert min(array, array.length) == Arrays.stream(array).min().getAsInt(); 25 | } 26 | 27 | /** 28 | * Get min of array using divide and conquer algorithm 29 | * 30 | * @param array contains elements 31 | * @param low the index of the first element 32 | * @param high the index of the last element 33 | * @return min of {@code array} 34 | */ 35 | public static int min(int[] array, int low, int high) { 36 | if (low == high) { 37 | return array[low]; // or array[high] 38 | } 39 | 40 | int mid = (low + high) >>> 1; 41 | 42 | int leftMin = min(array, low, mid); // get min in [low, mid] 43 | int rightMin = min(array, mid + 1, high); // get min in [mid+1, high] 44 | 45 | return Math.min(leftMin, rightMin); 46 | } 47 | 48 | /** 49 | * Get min of array using recursion algorithm 50 | * 51 | * @param array contains elements 52 | * @param len length of given array 53 | * @return min value of {@code array} 54 | */ 55 | public static int min(int[] array, int len) { 56 | return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Floor.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class Floor { 6 | 7 | public static void main(String[] args) { 8 | Random random = new Random(); 9 | for (int i = 1; i <= 1000; ++i) { 10 | double randomNumber = random.nextDouble(); 11 | assert floor(randomNumber) == Math.floor(randomNumber); 12 | } 13 | } 14 | 15 | /** 16 | * Returns the largest (closest to positive infinity) 17 | * 18 | * @param number the number 19 | * @return the largest (closest to positive infinity) of given 20 | * {@code number} 21 | */ 22 | public static double floor(double number) { 23 | if (number - (int) number == 0) { 24 | return number; 25 | } else if (number - (int) number > 0) { 26 | return (int) number; 27 | } else { 28 | return (int) number - 1; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GCD.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * This is Euclid's algorithm which is used to find the greatest common 5 | * denominator Overide function name gcd 6 | * 7 | * @author Oskar Enmalm 3/10/17 8 | */ 9 | public class GCD { 10 | 11 | /** 12 | * get greatest common divisor 13 | * 14 | * @param num1 the first number 15 | * @param num2 the second number 16 | * @return gcd 17 | */ 18 | public static int gcd(int num1, int num2) { 19 | if (num1 < 0 || num2 < 0) { 20 | throw new ArithmeticException(); 21 | } 22 | 23 | if (num1 == 0 || num2 == 0) { 24 | return Math.abs(num1 - num2); 25 | } 26 | 27 | while (num1 % num2 != 0) { 28 | int remainder = num1 % num2; 29 | num1 = num2; 30 | num2 = remainder; 31 | } 32 | return num2; 33 | } 34 | 35 | /** 36 | * get greatest common divisor in array 37 | * 38 | * @param number contains number 39 | * @return gcd 40 | */ 41 | public static int gcd(int[] number) { 42 | int result = number[0]; 43 | for (int i = 1; i < number.length; i++) // call gcd function (input two value) 44 | { 45 | result = gcd(result, number[i]); 46 | } 47 | 48 | return result; 49 | } 50 | 51 | public static void main(String[] args) { 52 | int[] myIntArray = {4, 16, 32}; 53 | 54 | // call gcd function (input array) 55 | System.out.println(gcd(myIntArray)); // => 4 56 | System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GCDRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * @author https://github.com/shellhub/ 5 | */ 6 | public class GCDRecursion { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(gcd(20, 15)); 10 | /* output: 5 */ 11 | System.out.println(gcd(10, 8)); 12 | /* output: 2 */ 13 | System.out.println(gcd(gcd(10, 5), gcd(5, 10))); 14 | /* output: 5 */ 15 | } 16 | 17 | /** 18 | * get greatest common divisor 19 | * 20 | * @param a the first number 21 | * @param b the second number 22 | * @return gcd 23 | */ 24 | public static int gcd(int a, int b) { 25 | 26 | if (a < 0 || b < 0) { 27 | throw new ArithmeticException(); 28 | } 29 | 30 | if (a == 0 || b == 0) { 31 | return Math.abs(a - b); 32 | } 33 | 34 | if (a % b == 0) { 35 | return b; 36 | } else { 37 | return gcd(b, a % b); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GenericRoot.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Algorithm explanation: https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015. 5 | */ 6 | public class GenericRoot { 7 | 8 | public static void main(String[] args) { 9 | int number1 = 1234; 10 | int number2 = 12345; 11 | int result1 = genericRoot(number1); 12 | int result2 = genericRoot(number2); 13 | System.out.println("Generic root of " + number1 + " is: " + result1); 14 | System.out.println("Generic root of " + number2 + " is: " + result2); 15 | } 16 | 17 | private static int genericRoot(int n) { 18 | int root = 0; 19 | while (n > 0 || root > 9) { 20 | if (n == 0) { 21 | n = root; 22 | root = 0; 23 | } 24 | root += n % 10; 25 | n /= 10; 26 | } 27 | return root; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/HarshadNumber.java: -------------------------------------------------------------------------------- 1 | // Wikipedia for Harshad Number : https://en.wikipedia.org/wiki/Harshad_number 2 | package com.thealgorithms.maths; 3 | 4 | import java.util.Scanner; 5 | 6 | public class HarshadNumber { 7 | 8 | public static void main(String[] args) { 9 | Scanner sc = new Scanner(System.in); 10 | System.out.print("Enter a number : "); 11 | long a = sc.nextLong(); 12 | 13 | checkHarshadNumber(a); 14 | } 15 | 16 | /** 17 | * A function to check if a number is Harshad number or not 18 | * 19 | * @param a The number which should be checked 20 | */ 21 | public static void checkHarshadNumber(long a) { 22 | 23 | long b = a; 24 | int sum = 0; 25 | 26 | // this is just for showing the explanation else it's of no use you can ommit it 27 | int[] each = new int[Long.toString(a).length()]; 28 | 29 | int c = 0; 30 | 31 | while (b > 0) { 32 | sum += b % 10; 33 | each[c] = (int) (b % 10); 34 | b /= 10; 35 | c++; 36 | } 37 | 38 | if (a % sum == 0) { 39 | System.out.println(a + " is a Harshad Number"); 40 | 41 | // For you better explanation how is that a Harshad Number 42 | System.out.println("\nExplaination :"); 43 | 44 | for (int i = each.length - 1; i >= 0; i--) { 45 | System.out.print(each[i] + " "); 46 | if (i != 0) { 47 | System.out.print("+ "); 48 | } 49 | } 50 | 51 | System.out.println("= " + sum); 52 | System.out.println(sum + " × " + (a / sum) + " = " + a); 53 | } else { 54 | System.out.println(a + " is not a Harshad Number"); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/JugglerSequence.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /* 7 | * Java program for printing juggler sequence 8 | * Wikipedia: https://en.wikipedia.org/wiki/Juggler_sequence 9 | * 10 | * Author: Akshay Dubey (https://github.com/itsAkshayDubey) 11 | * 12 | * */ 13 | 14 | public class JugglerSequence { 15 | /** 16 | * This method prints juggler sequence starting with the number in the parameter 17 | * 18 | * @param inputNumber Number from which juggler sequence is to be started 19 | */ 20 | public static void jugglerSequence(int inputNumber) { 21 | // Copy method argument to a local variable 22 | int n = inputNumber; 23 | List seq = new ArrayList<>(); 24 | seq.add(n + ""); 25 | // Looping till n reaches 1 26 | while (n != 1) { 27 | int temp; 28 | // if previous term is even then 29 | // next term in the sequence is square root of previous term 30 | // if previous term is odd then 31 | // next term is floor value of 3 time the square root of previous term 32 | 33 | // Check if previous term is even or odd 34 | if (n % 2 == 0) { 35 | temp = (int) Math.floor(Math.sqrt(n)); 36 | } else { 37 | temp = (int) Math.floor(Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n)); 38 | } 39 | n = temp; 40 | seq.add(n + ""); 41 | } 42 | String res = String.join(",", seq); 43 | System.out.println(res); 44 | } 45 | 46 | // Driver code 47 | public static void main(String[] args) { 48 | jugglerSequence(3); 49 | // Output: 3,5,11,36,6,2,1 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/KaprekarNumbers.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | import java.util.*; 3 | 4 | public class KaprekarNumbers { 5 | 6 | /* This program demonstrates if a given number is Kaprekar Number or not. 7 | Kaprekar Number: A Kaprekar number is an n-digit number which its square can be split into two parts where the right part has n 8 | digits and sum of these parts is equal to the original number. */ 9 | 10 | // Provides a list of kaprekarNumber in a range 11 | public static ArrayList kaprekarNumberInRange(long start, long end) throws Exception { 12 | long n = end-start; 13 | if (n <0) throw new Exception("Invalid range"); 14 | ArrayList list = new ArrayList<>(); 15 | 16 | for (long i = start; i <= end; i++) { 17 | if (isKaprekarNumber(i)) list.add(i); 18 | } 19 | 20 | return list; 21 | } 22 | 23 | // Checks whether a given number is Kaprekar Number or not 24 | public static boolean isKaprekarNumber(long number) { 25 | long numberSquared = number * number; 26 | if(Long.toString(number).length() == Long.toString(numberSquared).length()){ 27 | return (number == numberSquared); 28 | } 29 | else{ 30 | long leftDigits1 = 0, leftDigits2; 31 | if(Long.toString(numberSquared).contains("0")){ 32 | leftDigits1 = Long.parseLong(Long.toString(numberSquared).substring(0, Long.toString(numberSquared).indexOf("0"))); 33 | } 34 | leftDigits2 = Long.parseLong(Long.toString(numberSquared).substring(0, (Long.toString(numberSquared).length() - Long.toString(number).length()))); 35 | long rightDigits = Long.parseLong(Long.toString(numberSquared).substring(Long.toString(numberSquared).length() - Long.toString(number).length())); 36 | return (number == (leftDigits1 + rightDigits)) || (number == (leftDigits2 + rightDigits)); 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/LeonardoNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class LeonardoNumber { 4 | 5 | public static int leonardoNumber(int n) { 6 | if (n < 0) { 7 | return 0; 8 | } 9 | if (n == 0 || n == 1) { 10 | return 1; 11 | } 12 | return (leonardoNumber(n - 1) + leonardoNumber(n - 2) + 1); 13 | } 14 | 15 | public static void main(String args[]) { 16 | for (int i = 0; i < 20; i++) { 17 | System.out.print(leonardoNumber(i) + " "); 18 | } 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/LucasSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Lucas_number 5 | */ 6 | public class LucasSeries { 7 | 8 | public static void main(String[] args) { 9 | assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2; 10 | assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1; 11 | assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3; 12 | assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4; 13 | assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7; 14 | assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11; 15 | assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123; 16 | } 17 | 18 | /** 19 | * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 20 | * 123, ....) using recursion 21 | * 22 | * @param n nth 23 | * @return nth number of lucas series 24 | */ 25 | public static int lucasSeries(int n) { 26 | return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); 27 | } 28 | 29 | /** 30 | * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 31 | * 123, ....) using iteration 32 | * 33 | * @param n nth 34 | * @return nth number of lucas series 35 | */ 36 | public static int lucasSeriesIteration(int n) { 37 | int previous = 2; 38 | int current = 1; 39 | for (int i = 1; i < n; i++) { 40 | int next = previous + current; 41 | previous = current; 42 | current = next; 43 | } 44 | return previous; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/MagicSquare.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.*; 4 | 5 | /*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n numbers in all 6 | rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n^2.*/ 7 | public class MagicSquare { 8 | 9 | public static void main(String[] args) { 10 | 11 | Scanner sc = new Scanner(System.in); 12 | System.out.print("Input a number: "); 13 | int num = sc.nextInt(); 14 | if ((num % 2 == 0) || (num <= 0)) { 15 | System.out.print("Input number must be odd and >0"); 16 | System.exit(0); 17 | } 18 | 19 | int[][] magic_square = new int[num][num]; 20 | 21 | int row_num = num / 2; 22 | int col_num = num - 1; 23 | magic_square[row_num][col_num] = 1; 24 | 25 | for (int i = 2; i <= num * num; i++) { 26 | if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) { 27 | row_num = (row_num - 1 + num) % num; 28 | col_num = (col_num + 1) % num; 29 | } else { 30 | col_num = (col_num - 1 + num) % num; 31 | } 32 | magic_square[row_num][col_num] = i; 33 | } 34 | 35 | // print the square 36 | for (int i = 0; i < num; i++) { 37 | for (int j = 0; j < num; j++) { 38 | if (magic_square[i][j] < 10) { 39 | System.out.print(" "); 40 | } 41 | if (magic_square[i][j] < 100) { 42 | System.out.print(" "); 43 | } 44 | System.out.print(magic_square[i][j] + " "); 45 | } 46 | System.out.println(); 47 | } 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/MaxValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class MaxValue { 6 | 7 | /** 8 | * Driver Code 9 | */ 10 | public static void main(String[] args) { 11 | Random rand = new Random(); 12 | 13 | /* test 100 times using rand numbers */ 14 | for (int i = 1; i <= 100; ++i) { 15 | /* generate number from -50 to 49 */ 16 | int a = rand.nextInt(100) - 50; 17 | int b = rand.nextInt(100) - 50; 18 | assert max(a, b) == Math.max(a, b); 19 | } 20 | } 21 | 22 | /** 23 | * Returns the greater of two {@code int} values. That is, the result is the 24 | * argument closer to the value of {@link Integer#MAX_VALUE}. If the 25 | * arguments have the same value, the result is that same value. 26 | * 27 | * @param a an argument. 28 | * @param b another argument. 29 | * @return the larger of {@code a} and {@code b}. 30 | */ 31 | public static int max(int a, int b) { 32 | return a >= b ? a : b; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Median.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Wikipedia: https://en.wikipedia.org/wiki/Median 7 | */ 8 | public class Median { 9 | 10 | public static void main(String[] args) { 11 | assert median(new int[]{0}) == 0; 12 | assert median(new int[]{1, 2}) == 1.5; 13 | assert median(new int[]{4, 1, 3, 2}) == 2.5; 14 | assert median(new int[]{1, 3, 3, 6, 7, 8, 9}) == 6; 15 | assert median(new int[]{1, 2, 3, 4, 5, 6, 8, 9}) == 4.5; 16 | } 17 | 18 | /** 19 | * Calculate average median 20 | * 21 | * @param values number series 22 | * @return median of given {@code values} 23 | */ 24 | public static double median(int[] values) { 25 | Arrays.sort(values); 26 | int length = values.length; 27 | return length % 2 == 0 28 | ? (values[length / 2] + values[length / 2 - 1]) / 2.0 29 | : values[length / 2]; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/MinValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class MinValue { 6 | 7 | /** 8 | * Driver Code 9 | */ 10 | public static void main(String[] args) { 11 | Random rand = new Random(); 12 | 13 | /* test 100 times using rand numbers */ 14 | for (int i = 1; i <= 100; ++i) { 15 | /* generate number from -50 to 49 */ 16 | int a = rand.nextInt(100) - 50; 17 | int b = rand.nextInt(100) - 50; 18 | assert min(a, b) == Math.min(a, b); 19 | } 20 | } 21 | 22 | /** 23 | * Returns the smaller of two {@code int} values. That is, the result the 24 | * argument closer to the value of {@link Integer#MIN_VALUE}. If the 25 | * arguments have the same value, the result is that same value. 26 | * 27 | * @param a an argument. 28 | * @param b another argument. 29 | * @return the smaller of {@code a} and {@code b}. 30 | */ 31 | public static int min(int a, int b) { 32 | return a <= b ? a : b; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class PalindromeNumber { 4 | 5 | public static void main(String[] args) { 6 | 7 | assert isPalindrome(12321); 8 | assert !isPalindrome(1234); 9 | assert isPalindrome(1); 10 | } 11 | 12 | /** 13 | * Check if {@code n} is palindrome number or not 14 | * 15 | * @param number the number 16 | * @return {@code true} if {@code n} is palindrome number, otherwise 17 | * {@code false} 18 | */ 19 | public static boolean isPalindrome(int number) { 20 | if (number < 0) { 21 | throw new IllegalArgumentException(number + ""); 22 | } 23 | int numberCopy = number; 24 | int reverseNumber = 0; 25 | while (numberCopy != 0) { 26 | int remainder = numberCopy % 10; 27 | reverseNumber = reverseNumber * 10 + remainder; 28 | numberCopy /= 10; 29 | } 30 | return number == reverseNumber; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/ParseInteger.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class ParseInteger { 4 | 5 | public static void main(String[] args) { 6 | assert parseInt("123") == Integer.parseInt("123"); 7 | assert parseInt("-123") == Integer.parseInt("-123"); 8 | assert parseInt("0123") == Integer.parseInt("0123"); 9 | assert parseInt("+123") == Integer.parseInt("+123"); 10 | } 11 | 12 | /** 13 | * Parse a string to integer 14 | * 15 | * @param s the string 16 | * @return the integer value represented by the argument in decimal. 17 | * @throws NumberFormatException if the {@code string} does not contain a 18 | * parsable integer. 19 | */ 20 | public static int parseInt(String s) { 21 | if (s == null || s.length() == 0) { 22 | throw new NumberFormatException("null"); 23 | } 24 | boolean isNegative = s.charAt(0) == '-'; 25 | boolean isPositive = s.charAt(0) == '+'; 26 | int number = 0; 27 | for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) { 28 | if (!Character.isDigit(s.charAt(i))) { 29 | throw new NumberFormatException("s=" + s); 30 | } 31 | number = number * 10 + s.charAt(i) - '0'; 32 | } 33 | return isNegative ? -number : number; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PerfectCube.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Cube_(algebra) 5 | */ 6 | public class PerfectCube { 7 | 8 | public static void main(String[] args) { 9 | assert !isPerfectCube(-1); 10 | assert isPerfectCube(0); 11 | assert isPerfectCube(1); 12 | assert !isPerfectCube(4); 13 | assert isPerfectCube(8); 14 | assert isPerfectCube(27); 15 | } 16 | 17 | /** 18 | * Check if a number is perfect cube or not 19 | * 20 | * @param number number to check 21 | * @return {@code true} if {@code number} is perfect cube, otherwise 22 | * {@code false} 23 | */ 24 | public static boolean isPerfectCube(int number) { 25 | int a = (int) Math.pow(number, 1.0 / 3); 26 | return a * a * a == number; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PerfectNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * In number theory, a perfect number is a positive integer that is equal to the 5 | * sum of its positive divisors, excluding the number itself. For instance, 6 6 | * has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a 7 | * perfect number. 8 | * 9 | *

10 | * link:https://en.wikipedia.org/wiki/Perfect_number 11 | */ 12 | public class PerfectNumber { 13 | 14 | public static void main(String[] args) { 15 | assert isPerfectNumber(6); 16 | /* 1 + 2 + 3 == 6 */ 17 | assert !isPerfectNumber(8); 18 | /* 1 + 2 + 4 != 8 */ 19 | assert isPerfectNumber(28); 20 | /* 1 + 2 + 4 + 7 + 14 == 28 */ 21 | } 22 | 23 | /** 24 | * Check if {@code number} is perfect number or not 25 | * 26 | * @param number the number 27 | * @return {@code true} if {@code number} is perfect number, otherwise false 28 | */ 29 | public static boolean isPerfectNumber(int number) { 30 | int sum = 0; 31 | /* sum of its positive divisors */ 32 | for (int i = 1; i < number; ++i) { 33 | if (number % i == 0) { 34 | sum += i; 35 | } 36 | } 37 | return sum == number; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PerfectSquare.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Perfect_square 5 | */ 6 | public class PerfectSquare { 7 | 8 | public static void main(String[] args) { 9 | assert !isPerfectSquare(-1); 10 | assert !isPerfectSquare(3); 11 | assert !isPerfectSquare(5); 12 | assert isPerfectSquare(9); 13 | assert isPerfectSquare(100); 14 | } 15 | 16 | /** 17 | * Check if a number is perfect square number 18 | * 19 | * @param number the number to be checked 20 | * @return true if {@code number} is perfect square, otherwise 21 | * false 22 | */ 23 | public static boolean isPerfectSquare(int number) { 24 | int sqrt = (int) Math.sqrt(number); 25 | return sqrt * sqrt == number; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PiNilakantha.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class PiNilakantha { 4 | 5 | // Calculates Pi using Nilakantha's infinite series 6 | // Method 2 in the following link explains the algorithm 7 | // https://en.scratch-wiki.info/wiki/Calculating_Pi 8 | public static void main(String[] args) { 9 | assert calculatePi(0) == 3.0; 10 | assert calculatePi(10) > 3.0; 11 | assert calculatePi(100) < 4.0; 12 | 13 | System.out.println(calculatePi(500)); 14 | } 15 | 16 | /** 17 | * @param iterations number of times the infinite series gets repeated Pi 18 | * get more accurate the higher the value of iterations is Values from 0 up 19 | * to 500 are allowed since double precision is not sufficient for more than 20 | * about 500 repetitions of this algorithm 21 | * @return the pi value of the calculation with a precision of x iteration 22 | */ 23 | public static double calculatePi(int iterations) { 24 | if (iterations < 0 || iterations > 500) { 25 | throw new IllegalArgumentException("Please input Integer Number between 0 and 500"); 26 | } 27 | 28 | double pi = 3; 29 | int divCounter = 2; 30 | 31 | for (int i = 0; i < iterations; i++) { 32 | 33 | if (i % 2 == 0) { 34 | pi = pi + 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); 35 | } else { 36 | pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); 37 | } 38 | 39 | divCounter += 2; 40 | } 41 | return pi; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Pow.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | // POWER (exponentials) Examples (a^b) 4 | public class Pow { 5 | 6 | public static void main(String[] args) { 7 | assert pow(2, 0) == Math.pow(2, 0); // == 1 8 | assert pow(0, 2) == Math.pow(0, 2); // == 0 9 | assert pow(2, 10) == Math.pow(2, 10); // == 1024 10 | assert pow(10, 2) == Math.pow(10, 2); // == 100 11 | } 12 | 13 | /** 14 | * Returns the value of the first argument raised to the power of the second 15 | * argument 16 | * 17 | * @param a the base. 18 | * @param b the exponent. 19 | * @return the value {@code a}{@code b}. 20 | */ 21 | public static long pow(int a, int b) { 22 | long result = 1; 23 | for (int i = 1; i <= b; i++) { 24 | result *= a; 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PowRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class PowRecursion { 4 | 5 | public static void main(String[] args) { 6 | assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0; 7 | assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0; 8 | assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0; 9 | assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0; 10 | } 11 | 12 | /** 13 | * Returns the value of the first argument raised to the power of the second 14 | * argument 15 | * 16 | * @param a the base. 17 | * @param b the exponent. 18 | * @return the value {@code a}{@code b}. 19 | */ 20 | public static long pow(int a, int b) { 21 | return b == 0 ? 1 : a * pow(a, b - 1); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PowerOfTwoOrNot.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * A utility to check if a given number is power of two or not. For example 8,16 5 | * etc. 6 | */ 7 | public class PowerOfTwoOrNot { 8 | 9 | public static void main(String[] args) { 10 | assert !checkIfPowerOfTwoOrNot(0); 11 | assert checkIfPowerOfTwoOrNot(1); 12 | assert checkIfPowerOfTwoOrNot(8); 13 | assert checkIfPowerOfTwoOrNot(16); 14 | assert checkIfPowerOfTwoOrNot(1024); 15 | } 16 | 17 | /** 18 | * Checks whether given number is power of two or not. 19 | * 20 | * @param number the number to check 21 | * @return {@code true} if given number is power of two, otherwise 22 | * {@code false} 23 | */ 24 | public static boolean checkIfPowerOfTwoOrNot(int number) { 25 | return number != 0 && ((number & (number - 1)) == 0); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PrimeCheck.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PrimeCheck { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | 10 | System.out.print("Enter a number: "); 11 | int n = scanner.nextInt(); 12 | if (isPrime(n)) { 13 | System.out.println(n + " is a prime number"); 14 | } else { 15 | System.out.println(n + " is not a prime number"); 16 | } 17 | scanner.close(); 18 | } 19 | 20 | /** 21 | * * 22 | * Checks if a number is prime or not 23 | * 24 | * @param n the number 25 | * @return {@code true} if {@code n} is prime 26 | */ 27 | public static boolean isPrime(int n) { 28 | if (n == 2) { 29 | return true; 30 | } 31 | if (n < 2 || n % 2 == 0) { 32 | return false; 33 | } 34 | for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { 35 | if (n % i == 0) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PrimeFactorization.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PrimeFactorization { 6 | 7 | public static void main(String[] args) { 8 | System.out.println("## all prime factors ##"); 9 | Scanner scanner = new Scanner(System.in); 10 | System.out.print("Enter a number: "); 11 | int n = scanner.nextInt(); 12 | System.out.print(("printing factors of " + n + " : ")); 13 | pfactors(n); 14 | scanner.close(); 15 | } 16 | 17 | public static void pfactors(int n) { 18 | 19 | while (n % 2 == 0) { 20 | System.out.print(2 + " "); 21 | n /= 2; 22 | } 23 | 24 | for (int i = 3; i <= Math.sqrt(n); i += 2) { 25 | while (n % i == 0) { 26 | System.out.print(i + " "); 27 | n /= i; 28 | } 29 | } 30 | 31 | if (n > 2) { 32 | System.out.print(n); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PronicNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Java program for Pronic Number 5 | * Pronic Number: A number n is a pronic number if 6 | * it is equal to product of two consecutive numbers m and m+1. 7 | * Wikipedia: https://en.wikipedia.org/wiki/Pronic_number 8 | * 9 | * Author: Akshay Dubey (https://github.com/itsAkshayDubey) 10 | * 11 | * */ 12 | 13 | public class PronicNumber { 14 | 15 | /** 16 | * This method checks if the given number is pronic number or non-pronic number 17 | * 18 | * @param input_number Integer value which is to be checked if is a pronic number or not 19 | * @return true if input number is a pronic number, false otherwise 20 | */ 21 | static boolean isPronic(int input_number) { 22 | 23 | //Iterating from 0 to input_number 24 | for(int i = 0; i <= input_number; i++) { 25 | 26 | //Checking if product of i and (i+1) is equals input_number 27 | if(i * (i+1) == input_number && i != input_number) { 28 | 29 | //return true if product of i and (i+1) is equals input_number 30 | return true; 31 | } 32 | 33 | } 34 | 35 | //return false if product of i and (i+1) for all values from 0 to input_number is not equals input_number 36 | return false; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PythagoreanTriple.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Pythagorean_triple 5 | */ 6 | public class PythagoreanTriple { 7 | 8 | public static void main(String[] args) { 9 | assert isPythagTriple(3, 4, 5); 10 | assert isPythagTriple(5, 12, 13); 11 | assert isPythagTriple(6, 8, 10); 12 | assert !isPythagTriple(10, 20, 30); 13 | assert !isPythagTriple(6, 8, 100); 14 | assert !isPythagTriple(-1, -1, 1); 15 | } 16 | 17 | /** 18 | * Check if a,b,c are a Pythagorean Triple 19 | * 20 | * @param a x/y component length of a right triangle 21 | * @param b y/x component length of a right triangle 22 | * @param c hypotenuse length of a right triangle 23 | * @return boolean true if a, b, c satisfy the Pythagorean theorem, 24 | * otherwise 25 | * false 26 | */ 27 | public static boolean isPythagTriple(int a, int b, int c) { 28 | if (a <= 0 || b <= 0 || c <= 0) { 29 | return false; 30 | } else { 31 | return (a * a) + (b * b) == (c * c); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/ReverseNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Scanner; 4 | import java.util.NoSuchElementException; 5 | import java.lang.IllegalStateException; 6 | 7 | public class ReverseNumber { 8 | 9 | public static void main(String[] args) { 10 | int number; 11 | int reverse = 0; 12 | 13 | try (Scanner sc = new Scanner(System.in)) { 14 | System.out.println("Enter a number:"); 15 | number = sc.nextInt(); 16 | } catch (NoSuchElementException | IllegalStateException e) { 17 | System.out.println("ERROR: Invalid input"); 18 | return; 19 | } 20 | 21 | while (number != 0) { 22 | int remainder = number % 10; 23 | 24 | reverse = reverse * 10 + remainder; 25 | number = number / 10; 26 | } 27 | 28 | System.out.println("The reverse of the given number is: " + reverse); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Translates numbers into the Roman Numeral System. 5 | * 6 | * @see Roman 7 | * numerals 8 | * @author Sokratis Fotkatzikis 9 | * @version 1.0 10 | */ 11 | public class RomanNumeralUtil { 12 | 13 | private static final int MIN_VALUE = 1; 14 | private static final int MAX_VALUE = 5999; 15 | //1000-5999 16 | private static final String[] RN_M = {"", "M", "MM", "MMM", "MMMM", "MMMMM"}; 17 | //100-900 18 | private static final String[] RN_C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 19 | //10-90 20 | private static final String[] RN_X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 21 | //1-9 22 | private static final String[] RN_I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 23 | 24 | public static String generate(int number) { 25 | if (number < MIN_VALUE || number > MAX_VALUE) { 26 | throw new IllegalArgumentException( 27 | String.format( 28 | "The number must be in the range [%d, %d]", 29 | MIN_VALUE, 30 | MAX_VALUE 31 | ) 32 | ); 33 | } 34 | 35 | return RN_M[number / 1000] 36 | + RN_C[number % 1000 / 100] 37 | + RN_X[number % 100 / 10] 38 | + RN_I[number % 10]; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * In mathematics, an arithmetic progression (AP) or arithmetic sequence is a 5 | * sequence of numbers such that the difference between the consecutive terms is 6 | * constant. Difference here means the second minus the first. For instance, the 7 | * sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic progression with common 8 | * difference of 2. 9 | * 10 | *

11 | * Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression 12 | */ 13 | public class SumOfArithmeticSeries { 14 | 15 | public static void main(String[] args) { 16 | 17 | /* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */ 18 | assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0; 19 | 20 | /* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */ 21 | assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0; 22 | 23 | /* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */ 24 | assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0; 25 | 26 | /* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */ 27 | assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0; 28 | 29 | assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0; 30 | } 31 | 32 | /** 33 | * Calculate sum of arithmetic series 34 | * 35 | * @param firstTerm the initial term of an arithmetic series 36 | * @param commonDiff the common difference of an arithmetic series 37 | * @param numOfTerms the total terms of an arithmetic series 38 | * @return sum of given arithmetic series 39 | */ 40 | private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) { 41 | return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/TrinomialTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * The trinomial triangle is a variation of Pascal’s triangle. The difference 5 | * between the two is that an entry in the trinomial triangle is the sum of the 6 | * three (rather than the two in Pasacal’s triangle) entries above it 7 | * 8 | * Example Input: n = 4 Output 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 9 | */ 10 | public class TrinomialTriangle { 11 | 12 | public static int TrinomialValue(int n, int k) { 13 | if (n == 0 && k == 0) { 14 | return 1; 15 | } 16 | 17 | if (k < -n || k > n) { 18 | return 0; 19 | } 20 | 21 | return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); 22 | } 23 | 24 | public static void printTrinomial(int n) { 25 | for (int i = 0; i < n; i++) { 26 | for (int j = -i; j <= 0; j++) { 27 | System.out.print(TrinomialValue(i, j) + " "); 28 | } 29 | 30 | for (int j = 1; j <= i; j++) { 31 | System.out.print(TrinomialValue(i, j) + " "); 32 | } 33 | 34 | System.out.println(); 35 | } 36 | } 37 | 38 | public static void main(String argc[]) { 39 | int n = 6; 40 | printTrinomial(n); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/minimizinglateness/lateness_data.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 3 6 3 | 2 8 4 | 1 9 5 | 4 9 6 | 3 14 7 | 2 15 -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | 6 | /** 7 | * @author shrutisheoran 8 | */ 9 | public class MedianOfRunningArray { 10 | 11 | private PriorityQueue p1; 12 | private PriorityQueue p2; 13 | 14 | // Constructor 15 | public MedianOfRunningArray() { 16 | this.p1 = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap 17 | this.p2 = new PriorityQueue<>(); // Min Heap 18 | } 19 | 20 | /* 21 | Inserting lower half of array to max Heap 22 | and upper half to min heap 23 | */ 24 | public void insert(Integer e) { 25 | p2.add(e); 26 | if (p2.size() - p1.size() > 1) { 27 | p1.add(p2.remove()); 28 | } 29 | } 30 | 31 | /* 32 | Returns median at any given point 33 | */ 34 | public Integer median() { 35 | if (p1.size() == p2.size()) { 36 | return (p1.peek() + p2.peek()) / 2; 37 | } 38 | return p1.size() > p2.size() ? p1.peek() : p2.peek(); 39 | } 40 | 41 | public static void main(String[] args) { 42 | /* 43 | Testing the median function 44 | */ 45 | 46 | MedianOfRunningArray p = new MedianOfRunningArray(); 47 | int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; 48 | for (int i = 0; i < 9; i++) { 49 | p.insert(arr[i]); 50 | System.out.print(p.median() + " "); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/PalindromePrime.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PalindromePrime { 6 | 7 | public static void main(String[] args) { // Main funtion 8 | Scanner in = new Scanner(System.in); 9 | System.out.println("Enter the quantity of First Palindromic Primes you want"); 10 | int n = in.nextInt(); // Input of how many first palindromic prime we want 11 | functioning(n); // calling function - functioning 12 | in.close(); 13 | } 14 | 15 | public static boolean prime(int num) { // checking if number is prime or not 16 | for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) { 17 | if (num % divisor == 0) { 18 | return false; // false if not prime 19 | } 20 | } 21 | return true; // True if prime 22 | } 23 | 24 | public static int reverse(int n) { // Returns the reverse of the number 25 | int reverse = 0; 26 | while (n != 0) { 27 | reverse *= 10; 28 | reverse += n % 10; 29 | n /= 10; 30 | } 31 | return reverse; 32 | } 33 | 34 | public static void functioning(int y) { 35 | if (y == 0) { 36 | return; 37 | } 38 | System.out.print(2 + "\n"); // print the first Palindromic Prime 39 | int count = 1; 40 | int num = 3; 41 | while (count < y) { 42 | if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same 43 | count++; // counts check when to terminate while loop 44 | System.out.print(num + "\n"); // print the Palindromic Prime 45 | } 46 | num += 2; // inrease iterator value by two 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Stack; 4 | import com.thealgorithms.datastructures.lists.SinglyLinkedList; 5 | 6 | /** 7 | * A simple way of knowing if a singly linked list is palindrome is to push all 8 | * the values into a Stack and then compare the list to popped vales from the 9 | * Stack. 10 | * 11 | * See more: 12 | * https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ 13 | */ 14 | public class PalindromeSinglyLinkedList { 15 | 16 | public static void main(String[] args) { 17 | SinglyLinkedList linkedList = new SinglyLinkedList(); 18 | 19 | linkedList.insertHead(3); 20 | linkedList.insertNth(2, 1); 21 | linkedList.insertNth(1, 2); 22 | linkedList.insertNth(2, 3); 23 | linkedList.insertNth(3, 4); 24 | 25 | if (isPalindrome(linkedList)) { 26 | System.out.println("It's a palindrome list"); 27 | } else { 28 | System.out.println("It's NOT a palindrome list"); 29 | } 30 | } 31 | 32 | public static boolean isPalindrome(SinglyLinkedList linkedList) { 33 | boolean ret = true; 34 | Stack linkedListValues = new Stack<>(); 35 | 36 | for (int i = 0; i < linkedList.size(); i++) { 37 | linkedListValues.push(linkedList.getNth(i)); 38 | } 39 | 40 | for (int i = 0; i < linkedList.size(); i++) { 41 | if (linkedList.getNth(i) != linkedListValues.pop()) { 42 | ret = false; 43 | break; 44 | } 45 | } 46 | 47 | return ret; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/Sparcity.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.*; 4 | 5 | /* 6 | *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse). 7 | *The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse. 8 | * 9 | * @author Ojasva Jain 10 | */ 11 | 12 | class Sparcity { 13 | 14 | /* 15 | * @return Sparcity of matrix 16 | * 17 | * where sparcity = number of zeroes/total elements in matrix 18 | * 19 | */ 20 | static double sparcity(double[][] mat) { 21 | int zero = 0; 22 | //Traversing the matrix to count number of zeroes 23 | for (int i = 0; i < mat.length; i++) { 24 | for (int j = 0; j < mat[i].length; j++) { 25 | if (mat[i][j] == 0) { 26 | zero++; 27 | } 28 | } 29 | } 30 | //return sparcity 31 | return ((double) zero / (mat.length * mat[1].length)); 32 | } 33 | 34 | //Driver method 35 | public static void main(String[] args) { 36 | Scanner in = new Scanner(System.in); 37 | System.out.println("Enter number of rows in matrix: "); 38 | int n = in.nextInt(); 39 | System.out.println("Enter number of Columns in matrix: "); 40 | int m = in.nextInt(); 41 | 42 | System.out.println("Enter Matrix elements: "); 43 | double[][] mat = new double[n][m]; 44 | for (int i = 0; i < n; i++) { 45 | for (int j = 0; j < m; j++) { 46 | mat[i][j] = in.nextDouble(); 47 | } 48 | } 49 | System.out.println("Sparcity of matrix is: " + sparcity(mat)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/ArrayLeftRotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /* 4 | * A left rotation operation on an array 5 | * shifts each of the array's elements 6 | * given integer n unit to the left. 7 | * 8 | * @author sangin-lee 9 | */ 10 | 11 | public class ArrayLeftRotation { 12 | 13 | /* 14 | * Returns the result of left rotation of given array arr and integer n 15 | * 16 | * @param arr : int[] given array 17 | * 18 | * @param n : int given integer 19 | * 20 | * @return : int[] result of left rotation 21 | */ 22 | public static int[] rotateLeft(int[] arr, int n) { 23 | int size = arr.length; 24 | int[] dst = new int[size]; 25 | n = n % size; 26 | for(int i = 0; i < size; i++) { 27 | dst[i] = arr[n]; 28 | n = (n + 1) % size; 29 | } 30 | return dst; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/BoyerMoore.java: -------------------------------------------------------------------------------- 1 | /* this Code is the illustration of Boyer moore's voting algorithm to 2 | find the majority element is an array that appears more than n/2 times in an array 3 | where "n" is the length of the array. 4 | For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm 5 | */ 6 | package com.thealgorithms.others; 7 | 8 | import java.util.*; 9 | 10 | public class BoyerMoore { 11 | 12 | public static int findmajor(int[] a) { 13 | int count = 0; 14 | int cand = -1; 15 | for (int i = 0; i < a.length; i++) { 16 | if (count == 0) { 17 | cand = a[i]; 18 | count = 1; 19 | } else { 20 | if (a[i] == cand) { 21 | count++; 22 | } else { 23 | count--; 24 | } 25 | } 26 | } 27 | for (int i = 0; i < a.length; i++) { 28 | if (a[i] == cand) { 29 | count++; 30 | } 31 | } 32 | if (count > (a.length / 2)) { 33 | return cand; 34 | } 35 | return -1; 36 | } 37 | 38 | public static void main(String args[]) { 39 | Scanner input = new Scanner(System.in); 40 | int n = input.nextInt(); 41 | int a[] = new int[n]; 42 | for (int i = 0; i < n; i++) { 43 | a[i] = input.nextInt(); 44 | } 45 | System.out.println("the majority element is " + findmajor(a)); 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @author Nishita Aggarwal 7 | *

8 | * Brian Kernighan’s Algorithm 9 | *

10 | * algorithm to count the number of set bits in a given number 11 | *

12 | * Subtraction of 1 from a number toggles all the bits (from right to left) till 13 | * the rightmost set bit(including the rightmost set bit). So if we subtract a 14 | * number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the 15 | * rightmost set bit. 16 | *

17 | * If we do n & (n-1) in a loop and count the no of times loop executes we get 18 | * the set bit count. 19 | *

20 | *

21 | * Time Complexity: O(logn) 22 | */ 23 | public class BrianKernighanAlgorithm { 24 | 25 | /** 26 | * @param num: number in which we count the set bits 27 | * @return int: Number of set bits 28 | */ 29 | static int countSetBits(int num) { 30 | int cnt = 0; 31 | while (num != 0) { 32 | num = num & (num - 1); 33 | cnt++; 34 | } 35 | return cnt; 36 | } 37 | 38 | /** 39 | * @param args : command line arguments 40 | */ 41 | public static void main(String args[]) { 42 | Scanner sc = new Scanner(System.in); 43 | int num = sc.nextInt(); 44 | int setBitCount = countSetBits(num); 45 | System.out.println(setBitCount); 46 | sc.close(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/CRC32.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.BitSet; 4 | 5 | /** 6 | * Generates a crc32 checksum for a given string or byte array 7 | */ 8 | public class CRC32 { 9 | 10 | public static void main(String[] args) { 11 | System.out.println(Integer.toHexString(crc32("Hello World"))); 12 | } 13 | 14 | public static int crc32(String str) { 15 | return crc32(str.getBytes()); 16 | } 17 | 18 | public static int crc32(byte[] data) { 19 | BitSet bitSet = BitSet.valueOf(data); 20 | int crc32 = 0xFFFFFFFF; // initial value 21 | for (int i = 0; i < data.length * 8; i++) { 22 | if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) { 23 | crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial 24 | } else { 25 | crc32 = (crc32 << 1); 26 | } 27 | } 28 | crc32 = Integer.reverse(crc32); // result reflect 29 | return crc32 ^ 0xFFFFFFFF; // final xor value 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/CountChar.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CountChar { 6 | 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Enter your text: "); 10 | String str = input.nextLine(); 11 | input.close(); 12 | System.out.println("There are " + CountCharacters(str) + " characters."); 13 | } 14 | 15 | /** 16 | * Count non space character in string 17 | * 18 | * @param str String to count the characters 19 | * @return number of character in the specified string 20 | */ 21 | private static int CountCharacters(String str) { 22 | return str.replaceAll("\\s", "").length(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/CountWords.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * You enter a string into this program, and it will return how many words were 7 | * in that particular string 8 | * 9 | * @author Marcus 10 | */ 11 | public class CountWords { 12 | 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.println("Enter your text: "); 16 | String str = input.nextLine(); 17 | 18 | System.out.println("Your text has " + wordCount(str) + " word(s)"); 19 | System.out.println("Your text has " + secondaryWordCount(str) + " word(s)"); 20 | input.close(); 21 | } 22 | 23 | private static int wordCount(String s) { 24 | if (s == null || s.isEmpty()) { 25 | return 0; 26 | } 27 | return s.trim().split("[\\s]+").length; 28 | } 29 | 30 | /** 31 | * counts the number of words in a sentence but ignores all potential 32 | * non-alphanumeric characters that do not represent a word. runs in O(n) 33 | * where n is the length of s 34 | * 35 | * @param s String: sentence with word(s) 36 | * @return int: number of words 37 | */ 38 | private static int secondaryWordCount(String s) { 39 | if (s == null || s.isEmpty()) { 40 | return 0; 41 | } 42 | StringBuilder sb = new StringBuilder(); 43 | for (char c : s.toCharArray()) { 44 | if (Character.isLetter(c) || Character.isDigit(c)) { 45 | sb.append(c); 46 | } 47 | } 48 | s = sb.toString(); 49 | return s.trim().split("[\\s]+").length; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/EulersFunction.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * You can read more about Euler's totient function 5 | * 6 | *

7 | * See https://en.wikipedia.org/wiki/Euler%27s_totient_function 8 | */ 9 | public class EulersFunction { 10 | // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time 11 | // complexity; 12 | 13 | public static int getEuler(int n) { 14 | int result = n; 15 | for (int i = 2; i * i <= n; i++) { 16 | if (n % i == 0) { 17 | while (n % i == 0) { 18 | n /= i; 19 | } 20 | result -= result / i; 21 | } 22 | } 23 | if (n > 1) { 24 | result -= result / n; 25 | } 26 | return result; 27 | } 28 | 29 | public static void main(String[] args) { 30 | for (int i = 1; i < 100; i++) { 31 | System.out.println(getEuler(i)); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/FibbonaciSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Fibonacci sequence, and characterized by the fact that every number after the 7 | * first two is the sum of the two preceding ones. 8 | * 9 | *

10 | * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,... 11 | * 12 | *

13 | * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number 14 | * 15 | * Problem Statement: print all Fibonacci numbers that are smaller than your 16 | * given input N 17 | */ 18 | public class FibbonaciSeries { 19 | 20 | public static void main(String[] args) { 21 | // Get input from the user 22 | Scanner scan = new Scanner(System.in); 23 | int n = scan.nextInt(); 24 | int first = 0, second = 1; 25 | scan.close(); 26 | while (first <= n) { 27 | // print first fibo 0 then add second fibo into it while updating second as well 28 | System.out.println(first); 29 | int next = first + second; 30 | first = second; 31 | second = next; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class FloydTriangle { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); 10 | int r = sc.nextInt(), n = 0; 11 | sc.close(); 12 | for (int i = 0; i < r; i++) { 13 | for (int j = 0; j <= i; j++) { 14 | System.out.print(++n + " "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/GuassLegendre.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * Guass Legendre Algorithm ref 5 | * https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm 6 | * 7 | * @author AKS1996 8 | */ 9 | public class GuassLegendre { 10 | 11 | public static void main(String[] args) { 12 | for (int i = 1; i <= 3; ++i) { 13 | System.out.println(pi(i)); 14 | } 15 | } 16 | 17 | static double pi(int l) { 18 | /* 19 | * l: No of loops to run 20 | */ 21 | 22 | double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; 23 | for (int i = 0; i < l; ++i) { 24 | double temp[] = update(a, b, t, p); 25 | a = temp[0]; 26 | b = temp[1]; 27 | t = temp[2]; 28 | p = temp[3]; 29 | } 30 | 31 | return Math.pow(a + b, 2) / (4 * t); 32 | } 33 | 34 | static double[] update(double a, double b, double t, double p) { 35 | double values[] = new double[4]; 36 | values[0] = (a + b) / 2; 37 | values[1] = Math.sqrt(a * b); 38 | values[2] = t - p * Math.pow(a - values[0], 2); 39 | values[3] = 2 * p; 40 | 41 | return values; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/HappyNumbersSeq.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Scanner; 6 | import java.util.Set; 7 | 8 | public class HappyNumbersSeq { 9 | private static final Set CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | System.out.print("Enter number: "); 14 | int n = in.nextInt(); 15 | while (n != 1 && !isSad(n)) { 16 | System.out.print(n + " "); 17 | n = sumSquares(n); 18 | } 19 | String res = n == 1 ? "1 Happy number" : "Sad number"; 20 | System.out.println(res); 21 | } 22 | 23 | private static int sumSquares(int n) { 24 | int s = 0; 25 | for (; n > 0; n /= 10) { 26 | int r = n % 10; 27 | s += r * r; 28 | } 29 | return s; 30 | } 31 | 32 | private static boolean isSad(int n) { 33 | return CYCLE_NUMS.contains(n); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/InsertDeleteInArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.*; 4 | 5 | public class InsertDeleteInArray { 6 | 7 | public static void main(String[] args) { 8 | Scanner s = new Scanner(System.in); // Input statement 9 | System.out.println("Enter the size of the array"); 10 | int size = s.nextInt(); 11 | int a[] = new int[size]; 12 | int i; 13 | 14 | // To enter the initial elements 15 | for (i = 0; i < size; i++) { 16 | System.out.println("Enter the element"); 17 | a[i] = s.nextInt(); 18 | } 19 | 20 | // To insert a new element(we are creating a new array) 21 | System.out.println("Enter the index at which the element should be inserted"); 22 | int insert_pos = s.nextInt(); 23 | System.out.println("Enter the element to be inserted"); 24 | int ins = s.nextInt(); 25 | int size2 = size + 1; 26 | int b[] = new int[size2]; 27 | for (i = 0; i < size2; i++) { 28 | if (i <= insert_pos) { 29 | b[i] = a[i]; 30 | } else { 31 | b[i] = a[i - 1]; 32 | } 33 | } 34 | b[insert_pos] = ins; 35 | for (i = 0; i < size2; i++) { 36 | System.out.println(b[i]); 37 | } 38 | 39 | // To delete an element given the index 40 | System.out.println("Enter the index at which element is to be deleted"); 41 | int del_pos = s.nextInt(); 42 | for (i = del_pos; i < size2 - 1; i++) { 43 | b[i] = b[i + 1]; 44 | } 45 | for (i = 0; i < size2 - 1; i++) { 46 | System.out.println(b[i]); 47 | } 48 | s.close(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/Krishnamurthy.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class Krishnamurthy { 6 | 7 | static int fact(int n) { 8 | int i, p = 1; 9 | for (i = n; i >= 1; i--) { 10 | p = p * i; 11 | } 12 | return p; 13 | } 14 | 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int a, b, s = 0; 18 | System.out.print("Enter the number : "); 19 | a = sc.nextInt(); 20 | int n = a; 21 | while (a > 0) { 22 | b = a % 10; 23 | s = s + fact(b); 24 | a = a / 10; 25 | } 26 | if (s == n) { 27 | System.out.print(n + " is a krishnamurthy number"); 28 | } else { 29 | System.out.print(n + " is not a krishnamurthy number"); 30 | } 31 | sc.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/PasswordGen.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Random; 7 | 8 | /** 9 | * Creates a random password from ASCII letters Given password length bounds 10 | * 11 | * @author AKS1996 12 | * @date 2017.10.25 13 | */ 14 | class PasswordGen { 15 | 16 | public static void main(String args[]) { 17 | String password = generatePassword(8, 16); 18 | System.out.print("Password: " + password); 19 | } 20 | 21 | static String generatePassword(int min_length, int max_length) { 22 | Random random = new Random(); 23 | 24 | String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 25 | String lower = "abcdefghijklmnopqrstuvwxyz"; 26 | String numbers = "0123456789"; 27 | String specialChars = "!@#$%^&*(){}?"; 28 | 29 | String allChars = upper + lower + numbers + specialChars; 30 | 31 | List letters = new ArrayList(); 32 | for (char c : allChars.toCharArray()) { 33 | letters.add(c); 34 | } 35 | 36 | // Inbuilt method to randomly shuffle a elements of a list 37 | Collections.shuffle(letters); 38 | StringBuilder password = new StringBuilder(); 39 | 40 | // Note that size of the password is also random 41 | for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { 42 | password.append(letters.get(random.nextInt(letters.size()))); 43 | } 44 | 45 | return password.toString(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | 6 | /** 7 | * @author Varun Upadhyay (https://github.com/varunu28) 8 | */ 9 | public class RemoveDuplicateFromString { 10 | 11 | public static void main(String[] args) throws Exception { 12 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 13 | String inpStr = br.readLine(); 14 | 15 | System.out.println("Actual string is: " + inpStr); 16 | System.out.println("String after removing duplicates: " + removeDuplicate(inpStr)); 17 | 18 | br.close(); 19 | } 20 | 21 | /** 22 | * This method produces a string after removing all the duplicate characters 23 | * from input string and returns it Example: Input String - "aabbbccccddddd" 24 | * Output String - "abcd" 25 | * 26 | * @param s String from which duplicate characters have to be removed 27 | * @return string with only unique characters 28 | */ 29 | public static String removeDuplicate(String s) { 30 | if (s == null || s.isEmpty()) { 31 | return s; 32 | } 33 | 34 | StringBuilder sb = new StringBuilder(); 35 | int n = s.length(); 36 | 37 | for (int i = 0; i < n; i++) { 38 | if (sb.toString().indexOf(s.charAt(i)) == -1) { 39 | sb.append(String.valueOf(s.charAt(i))); 40 | } 41 | } 42 | 43 | return sb.toString(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/RootPrecision.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class RootPrecision { 6 | 7 | public static void main(String[] args) { 8 | // take input 9 | Scanner scn = new Scanner(System.in); 10 | 11 | // N is the input number 12 | int N = scn.nextInt(); 13 | 14 | // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. 15 | int P = scn.nextInt(); 16 | System.out.println(squareRoot(N, P)); 17 | 18 | scn.close(); 19 | } 20 | 21 | public static double squareRoot(int N, int P) { 22 | // rv means return value 23 | double rv; 24 | 25 | double root = Math.pow(N, 0.5); 26 | 27 | // calculate precision to power of 10 and then multiply it with root value. 28 | int precision = (int) Math.pow(10, P); 29 | root = root * precision; 30 | /*typecast it into integer then divide by precision and again typecast into double 31 | so as to have decimal points upto P precision */ 32 | 33 | rv = (int) root; 34 | return rv / precision; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/StackPostfixNotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.*; 4 | 5 | public class StackPostfixNotation { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +" 10 | System.out.println(postfixEvaluate(post)); 11 | scanner.close(); 12 | } 13 | 14 | // Evaluates the given postfix expression string and returns the result. 15 | public static int postfixEvaluate(String exp) { 16 | Stack s = new Stack(); 17 | Scanner tokens = new Scanner(exp); 18 | 19 | while (tokens.hasNext()) { 20 | if (tokens.hasNextInt()) { 21 | s.push(tokens.nextInt()); // If int then push to stack 22 | } else { // else pop top two values and perform the operation 23 | int num2 = s.pop(); 24 | int num1 = s.pop(); 25 | String op = tokens.next(); 26 | 27 | if (op.equals("+")) { 28 | s.push(num1 + num2); 29 | } else if (op.equals("-")) { 30 | s.push(num1 - num2); 31 | } else if (op.equals("*")) { 32 | s.push(num1 * num2); 33 | } else { 34 | s.push(num1 / num2); 35 | } 36 | 37 | // "+", "-", "*", "/" 38 | } 39 | } 40 | tokens.close(); 41 | return s.pop(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/ThreeSum.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * To find triplet equals to given sum in complexity O(n*log(n)) 8 | * 9 | *

10 | * Array must be sorted 11 | * 12 | * @author Ujjawal Joshi 13 | * @date 2020.05.18 14 | *

15 | * Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12 16 | * Explanation: There is a triplet (12, 3 and 9) present in the array whose sum 17 | * is 24. 18 | */ 19 | class ThreeSum { 20 | 21 | public static void main(String args[]) { 22 | Scanner sc = new Scanner(System.in); 23 | int n = sc.nextInt(); // Length of an array 24 | 25 | int a[] = new int[n]; 26 | 27 | for (int i = 0; i < n; i++) { 28 | a[i] = sc.nextInt(); 29 | } 30 | System.out.println("Target"); 31 | int n_find = sc.nextInt(); 32 | 33 | Arrays.sort(a); // Sort the array if array is not sorted 34 | 35 | for (int i = 0; i < n; i++) { 36 | 37 | int l = i + 1, r = n - 1; 38 | 39 | while (l < r) { 40 | if (a[i] + a[l] + a[r] == n_find) { 41 | System.out.println(a[i] + " " + a[l] + " " + a[r]); 42 | break; 43 | } // if you want all the triplets write l++;r--; insted of break; 44 | else if (a[i] + a[l] + a[r] < n_find) { 45 | l++; 46 | } else { 47 | r--; 48 | } 49 | } 50 | } 51 | 52 | sc.close(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class TowerOfHanoi { 6 | 7 | public static void shift(int n, String startPole, String intermediatePole, String endPole) { 8 | // if n becomes zero the program returns thus ending the loop. 9 | if (n != 0) { 10 | // Shift function is called in recursion for swapping the n-1 disc from the startPole to the 11 | // intermediatePole 12 | shift(n - 1, startPole, endPole, intermediatePole); 13 | System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing 14 | // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole 15 | // to the endPole 16 | shift(n - 1, intermediatePole, startPole, endPole); 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.print("Enter number of discs on Pole 1: "); 22 | Scanner scanner = new Scanner(System.in); 23 | int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1 24 | shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called 25 | scanner.close(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/TwoPointers.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * The two pointer technique is a useful tool to utilize when searching for 7 | * pairs in a sorted array. 8 | * 9 | *

10 | * link: https://www.geeksforgeeks.org/two-pointers-technique/ 11 | */ 12 | class TwoPointers { 13 | 14 | public static void main(String[] args) { 15 | int[] arr = {10, 20, 35, 50, 75, 80}; 16 | int key = 70; 17 | assert isPairedSum(arr, key); 18 | /* 20 + 60 == 70 */ 19 | 20 | arr = new int[]{1, 2, 3, 4, 5, 6, 7}; 21 | key = 13; 22 | assert isPairedSum(arr, key); 23 | /* 6 + 7 == 13 */ 24 | 25 | key = 14; 26 | assert !isPairedSum(arr, key); 27 | } 28 | 29 | /** 30 | * Given a sorted array arr (sorted in ascending order). Find if there 31 | * exists any pair of elements such that their sum is equal to key. 32 | * 33 | * @param arr the array contains elements 34 | * @param key the number to search 35 | * @return {@code true} if there exists a pair of elements, {@code false} 36 | * otherwise. 37 | */ 38 | private static boolean isPairedSum(int[] arr, int key) { 39 | /* array sorting is necessary for this algorithm to function correctly */ 40 | Arrays.sort(arr); 41 | int i = 0; 42 | /* index of first element */ 43 | int j = arr.length - 1; 44 | /* index of last element */ 45 | 46 | while (i < j) { 47 | if (arr[i] + arr[j] == key) { 48 | return true; 49 | } else if (arr[i] + arr[j] < key) { 50 | i++; 51 | } else { 52 | j--; 53 | } 54 | } 55 | return false; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/searches/JumpSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 4 | 5 | public class JumpSearch implements SearchAlgorithm { 6 | 7 | public static void main(String[] args) { 8 | JumpSearch jumpSearch = new JumpSearch(); 9 | Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 10 | for (int i = 0; i < array.length; i++) { 11 | assert jumpSearch.find(array, i) == i; 12 | } 13 | assert jumpSearch.find(array, -1) == -1; 14 | assert jumpSearch.find(array, 11) == -1; 15 | } 16 | 17 | /** 18 | * Jump Search algorithm implements 19 | * 20 | * @param array the array contains elements 21 | * @param key to be searched 22 | * @return index of {@code key} if found, otherwise -1 23 | */ 24 | @Override 25 | public > int find(T[] array, T key) { 26 | int length = array.length; 27 | /* length of array */ 28 | int blockSize = (int) Math.sqrt(length); 29 | /* block size to be jumped */ 30 | 31 | int limit = blockSize; 32 | while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) { 33 | limit = Math.min(limit + blockSize, array.length - 1); 34 | } 35 | 36 | for (int i = limit - blockSize; i <= limit; i++) { 37 | if (array[i] == key) { 38 | /* execute linear search */ 39 | return i; 40 | } 41 | } 42 | return -1; 43 | /* not found */ 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | class PerfectBinarySearch { 4 | 5 | static int binarySearch(int[] arr, int target) { 6 | int low = 0; 7 | int high = arr.length - 1; 8 | 9 | while (low <= high) { 10 | int mid = (low + high) / 2; 11 | 12 | if (arr[mid] == target) { 13 | return mid; 14 | } else if (arr[mid] > target) { 15 | high = mid - 1; 16 | } else { 17 | low = mid + 1; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | public static void main(String[] args) { 24 | PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); 25 | int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 26 | assert BinarySearch.binarySearch(array, -1) == -1; 27 | assert BinarySearch.binarySearch(array, 11) == -1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/BogoSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * @author Podshivalov Nikita (https://github.com/nikitap492) 7 | * @see SortAlgorithm 8 | */ 9 | public class BogoSort implements SortAlgorithm { 10 | 11 | private static final Random random = new Random(); 12 | 13 | private static > boolean isSorted(T[] array) { 14 | for (int i = 0; i < array.length - 1; i++) { 15 | if (SortUtils.less(array[i + 1], array[i])) { 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | 22 | // Randomly shuffles the array 23 | private static void nextPermutation(T[] array) { 24 | int length = array.length; 25 | 26 | for (int i = 0; i < array.length; i++) { 27 | int randomIndex = i + random.nextInt(length - i); 28 | SortUtils.swap(array, randomIndex, i); 29 | } 30 | } 31 | 32 | public > T[] sort(T[] array) { 33 | while (!isSorted(array)) { 34 | nextPermutation(array); 35 | } 36 | return array; 37 | } 38 | 39 | // Driver Program 40 | public static void main(String[] args) { 41 | // Integer Input 42 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 43 | 44 | BogoSort bogoSort = new BogoSort(); 45 | 46 | // print a sorted array 47 | SortUtils.print(bogoSort.sort(integers)); 48 | 49 | // String Input 50 | String[] strings = {"c", "a", "e", "b", "d"}; 51 | 52 | SortUtils.print(bogoSort.sort(strings)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/DNFSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class DNFSort { 4 | 5 | // Sort the input array, the array is assumed to 6 | // have values in {0, 1, 2} 7 | static void sort012(int a[], int arr_size) { 8 | int low = 0; 9 | int high = arr_size - 1; 10 | int mid = 0, temp = 0; 11 | while (mid <= high) { 12 | switch (a[mid]) { 13 | case 0: { 14 | temp = a[low]; 15 | a[low] = a[mid]; 16 | a[mid] = temp; 17 | low++; 18 | mid++; 19 | break; 20 | } 21 | case 1: 22 | mid++; 23 | break; 24 | case 2: { 25 | temp = a[mid]; 26 | a[mid] = a[high]; 27 | a[high] = temp; 28 | high--; 29 | break; 30 | } 31 | } 32 | } 33 | } 34 | 35 | /* Utility function to print array arr[] */ 36 | static void printArray(int arr[], int arr_size) { 37 | for (int i = 0; i < arr_size; i++) { 38 | System.out.print(arr[i] + " "); 39 | } 40 | System.out.println(""); 41 | } 42 | 43 | /*Driver function to check for above functions*/ 44 | public static void main(String[] args) { 45 | int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; 46 | int arr_size = arr.length; 47 | sort012(arr, arr_size); 48 | System.out.println("Array after seggregation "); 49 | printArray(arr, arr_size); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/GnomeSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | /** 6 | * Implementation of gnome sort 7 | * 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | * @since 2018-04-10 10 | */ 11 | public class GnomeSort implements SortAlgorithm { 12 | 13 | @Override 14 | public > T[] sort(T[] arr) { 15 | int i = 1; 16 | int j = 2; 17 | while (i < arr.length) { 18 | if (less(arr[i - 1], arr[i])) { 19 | i = j++; 20 | } else { 21 | swap(arr, i - 1, i); 22 | if (--i == 0) { 23 | i = j++; 24 | } 25 | } 26 | } 27 | 28 | return null; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; 33 | String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"}; 34 | GnomeSort gnomeSort = new GnomeSort(); 35 | 36 | gnomeSort.sort(integers); 37 | gnomeSort.sort(strings); 38 | 39 | System.out.println("After sort : "); 40 | print(integers); 41 | print(strings); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.less; 4 | import static com.thealgorithms.sorts.SortUtils.print; 5 | 6 | class InsertionSort implements SortAlgorithm { 7 | 8 | /** 9 | * Generic insertion sort algorithm in increasing order. 10 | * 11 | * @param array the array to be sorted. 12 | * @param the class of array. 13 | * @return sorted array. 14 | */ 15 | @Override 16 | public > T[] sort(T[] array) { 17 | for (int i = 1; i < array.length; i++) { 18 | T insertValue = array[i]; 19 | int j; 20 | for (j = i - 1; j >= 0 && less(insertValue, array[j]); j--) { 21 | array[j + 1] = array[j]; 22 | } 23 | if (j != i - 1) { 24 | array[j + 1] = insertValue; 25 | } 26 | } 27 | return array; 28 | } 29 | 30 | /** 31 | * Driver Code 32 | */ 33 | public static void main(String[] args) { 34 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 35 | InsertionSort sort = new InsertionSort(); 36 | sort.sort(integers); 37 | print(integers); 38 | /* [1, 4, 6, 9, 12, 23, 54, 78, 231] */ 39 | 40 | String[] strings = {"c", "a", "e", "b", "d"}; 41 | sort.sort(strings); 42 | print(strings); 43 | /* [a, b, c, d, e] */ 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/PancakeSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | /** 6 | * Implementation of pancake sort 7 | * 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | * @since 2018-04-10 10 | */ 11 | public class PancakeSort implements SortAlgorithm { 12 | 13 | @Override 14 | public > T[] sort(T[] array) { 15 | int size = array.length; 16 | 17 | for (int i = 0; i < size; i++) { 18 | T max = array[0]; 19 | int index = 0; 20 | for (int j = 0; j < size - i; j++) { 21 | if (less(max, array[j])) { 22 | max = array[j]; 23 | index = j; 24 | } 25 | } 26 | flip(array, index, array.length - 1 - i); 27 | } 28 | return array; 29 | } 30 | 31 | public static void main(String[] args) { 32 | 33 | Integer[] arr = { 34 | 10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1 35 | }; 36 | PancakeSort pancakeSort = new PancakeSort(); 37 | System.out.println("After sorting:"); 38 | pancakeSort.sort(arr); 39 | print(arr); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/RadixSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import java.util.Arrays; 4 | 5 | class RadixSort { 6 | 7 | private static int getMax(int[] arr, int n) { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) { 10 | if (arr[i] > mx) { 11 | mx = arr[i]; 12 | } 13 | } 14 | return mx; 15 | } 16 | 17 | private static void countSort(int[] arr, int n, int exp) { 18 | int[] output = new int[n]; 19 | int i; 20 | int[] count = new int[10]; 21 | Arrays.fill(count, 0); 22 | 23 | for (i = 0; i < n; i++) { 24 | count[(arr[i] / exp) % 10]++; 25 | } 26 | 27 | for (i = 1; i < 10; i++) { 28 | count[i] += count[i - 1]; 29 | } 30 | 31 | for (i = n - 1; i >= 0; i--) { 32 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 33 | count[(arr[i] / exp) % 10]--; 34 | } 35 | 36 | for (i = 0; i < n; i++) { 37 | arr[i] = output[i]; 38 | } 39 | } 40 | 41 | private static void radixsort(int[] arr, int n) { 42 | 43 | int m = getMax(arr, n); 44 | 45 | for (int exp = 1; m / exp > 0; exp *= 10) { 46 | countSort(arr, n, exp); 47 | } 48 | } 49 | 50 | static void print(int[] arr, int n) { 51 | for (int i = 0; i < n; i++) { 52 | System.out.print(arr[i] + " "); 53 | } 54 | } 55 | 56 | public static void main(String[] args) { 57 | int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; 58 | int n = arr.length; 59 | radixsort(arr, n); 60 | print(arr, n); 61 | } 62 | } 63 | // Written by James Mc Dermott(theycallmemac) 64 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class SelectionSort implements SortAlgorithm { 4 | 5 | /** 6 | * Generic selection sort algorithm in increasing order. 7 | * 8 | * @param arr the array to be sorted. 9 | * @param the class of array. 10 | * @return sorted array. 11 | */ 12 | @Override 13 | public > T[] sort(T[] arr) { 14 | int n = arr.length; 15 | for (int i = 0; i < n - 1; i++) { 16 | int minIndex = i; 17 | for (int j = i + 1; j < n; j++) { 18 | if (arr[minIndex].compareTo(arr[j]) > 0) { 19 | minIndex = j; 20 | } 21 | } 22 | if (minIndex != i) { 23 | T temp = arr[i]; 24 | arr[i] = arr[minIndex]; 25 | arr[minIndex] = temp; 26 | } 27 | } 28 | return arr; 29 | } 30 | 31 | /** 32 | * Driver Code 33 | */ 34 | public static void main(String[] args) { 35 | 36 | Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 37 | SelectionSort selectionSort = new SelectionSort(); 38 | Integer[] sorted = selectionSort.sort(arr); 39 | for (int i = 0; i < sorted.length - 1; ++i) { 40 | assert sorted[i] <= sorted[i + 1]; 41 | } 42 | 43 | String[] strings = {"c", "a", "e", "b", "d"}; 44 | String[] sortedStrings = selectionSort.sort(strings); 45 | for (int i = 0; i < sortedStrings.length - 1; ++i) { 46 | assert strings[i].compareTo(strings[i + 1]) <= 0; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/ShellSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | public class ShellSort implements SortAlgorithm { 6 | 7 | /** 8 | * Implements generic shell sort. 9 | * 10 | * @param array the array to be sorted. 11 | * @param the type of elements in the array. 12 | * @return the sorted array. 13 | */ 14 | @Override 15 | public > T[] sort(T[] array) { 16 | int length = array.length; 17 | int gap = 1; 18 | 19 | /* Calculate gap for optimization purpose */ 20 | while (gap < length / 3) { 21 | gap = 3 * gap + 1; 22 | } 23 | 24 | for (; gap > 0; gap /= 3) { 25 | for (int i = gap; i < length; i++) { 26 | int j; 27 | T temp = array[i]; 28 | for (j = i; j >= gap && less(temp, array[j - gap]); j -= gap) { 29 | array[j] = array[j - gap]; 30 | } 31 | array[j] = temp; 32 | } 33 | } 34 | return array; 35 | } 36 | 37 | /* Driver Code */ 38 | public static void main(String[] args) { 39 | Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 40 | 41 | ShellSort sort = new ShellSort(); 42 | sort.sort(toSort); 43 | for (int i = 0; i < toSort.length - 1; ++i) { 44 | assert toSort[i] <= toSort[i + 1]; 45 | } 46 | print(toSort); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SimpleSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | public class SimpleSort implements SortAlgorithm { 6 | 7 | @Override 8 | public > T[] sort(T[] array) { 9 | final int LENGTH = array.length; 10 | 11 | for (int i = 0; i < LENGTH; i++) { 12 | for (int j = i + 1; j < LENGTH; j++) { 13 | if (less(array[j], array[i])) { 14 | T element = array[j]; 15 | array[j] = array[i]; 16 | array[i] = element; 17 | } 18 | } 19 | } 20 | 21 | return array; 22 | } 23 | 24 | public static void main(String[] args) { 25 | // ==== Int ======= 26 | Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; 27 | System.out.print("unsorted: "); 28 | print(a); 29 | System.out.println(); 30 | 31 | new SimpleSort().sort(a); 32 | System.out.print("sorted: "); 33 | print(a); 34 | System.out.println(); 35 | 36 | // ==== String ======= 37 | String[] b = {"banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"}; 38 | System.out.print("unsorted: "); 39 | print(b); 40 | System.out.println(); 41 | 42 | new SimpleSort().sort(b); 43 | System.out.print("sorted: "); 44 | print(b); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SlowSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * @author Amir Hassan (https://github.com/ahsNT) 5 | * @see SortAlgorithm 6 | */ 7 | public class SlowSort implements SortAlgorithm { 8 | 9 | @Override 10 | public > T[] sort(T[] unsortedArray) { 11 | sort(unsortedArray, 0, unsortedArray.length - 1); 12 | return unsortedArray; 13 | } 14 | 15 | private > void sort(T[] array, int i, int j) { 16 | if (SortUtils.greaterOrEqual(i, j)) { 17 | return; 18 | } 19 | int m = (i + j) / 2; 20 | sort(array, i, m); 21 | sort(array, m + 1, j); 22 | if (SortUtils.less(array[j], array[m])) { 23 | T temp = array[j]; 24 | array[j] = array[m]; 25 | array[m] = temp; 26 | } 27 | sort(array, i, j - 1); 28 | } 29 | 30 | public static void main(String[] args) { 31 | SlowSort slowSort = new SlowSort(); 32 | 33 | Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202, 98}; 34 | // Print integerArray unsorted 35 | SortUtils.print(integerArray); 36 | 37 | slowSort.sort(integerArray); 38 | // Print integerArray sorted 39 | SortUtils.print(integerArray); 40 | 41 | String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; 42 | // Print stringArray unsorted 43 | SortUtils.print(stringArray); 44 | 45 | slowSort.sort(stringArray); 46 | // Print stringArray sorted 47 | SortUtils.print(stringArray); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SortAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * The common interface of most sorting algorithms 8 | * 9 | * @author Podshivalov Nikita (https://github.com/nikitap492) 10 | */ 11 | public interface SortAlgorithm { 12 | 13 | /** 14 | * Main method arrays sorting algorithms 15 | * 16 | * @param unsorted - an array should be sorted 17 | * @return a sorted array 18 | */ 19 | > T[] sort(T[] unsorted); 20 | 21 | /** 22 | * Auxiliary method for algorithms what wanted to work with lists from JCF 23 | * 24 | * @param unsorted - a list should be sorted 25 | * @return a sorted list 26 | */ 27 | @SuppressWarnings("unchecked") 28 | default > List sort(List unsorted) { 29 | return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/StoogeSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * @author Amir Hassan (https://github.com/ahsNT) 5 | * @see SortAlgorithm 6 | */ 7 | public class StoogeSort implements SortAlgorithm { 8 | 9 | @Override 10 | public > T[] sort(T[] unsortedArray) { 11 | sort(unsortedArray, 0, unsortedArray.length); 12 | return unsortedArray; 13 | } 14 | 15 | public > T[] sort(T[] unsortedArray, int start, int end) { 16 | if (SortUtils.less(unsortedArray[end - 1], unsortedArray[start])) { 17 | T temp = unsortedArray[start]; 18 | unsortedArray[start] = unsortedArray[end - 1]; 19 | unsortedArray[end - 1] = temp; 20 | } 21 | 22 | int len = end - start; 23 | if (len > 2) { 24 | int third = len / 3; 25 | sort(unsortedArray, start, end - third); 26 | sort(unsortedArray, start + third, end); 27 | sort(unsortedArray, start, end - third); 28 | } 29 | return unsortedArray; 30 | } 31 | 32 | public static void main(String[] args) { 33 | StoogeSort stoogeSort = new StoogeSort(); 34 | 35 | Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202}; 36 | // Print integerArray unsorted 37 | SortUtils.print(integerArray); 38 | 39 | stoogeSort.sort(integerArray); 40 | // Print integerArray sorted 41 | SortUtils.print(integerArray); 42 | 43 | String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; 44 | // Print stringArray unsorted 45 | SortUtils.print(stringArray); 46 | 47 | stoogeSort.sort(stringArray); 48 | // Print stringArray sorted 49 | SortUtils.print(stringArray); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Alphabetical.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Alphabetical order is a system whereby character strings are placed in order 5 | * based on the position of the characters in the conventional ordering of an 6 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 7 | */ 8 | class Alphabetical { 9 | 10 | public static void main(String[] args) { 11 | assert !isAlphabetical("123abc"); 12 | assert isAlphabetical("aBC"); 13 | assert isAlphabetical("abc"); 14 | assert !isAlphabetical("xyzabc"); 15 | assert isAlphabetical("abcxyz"); 16 | } 17 | 18 | /** 19 | * Check if a string is alphabetical order or not 20 | * 21 | * @param s a string 22 | * @return {@code true} if given string is alphabetical order, otherwise 23 | * {@code false} 24 | */ 25 | public static boolean isAlphabetical(String s) { 26 | s = s.toLowerCase(); 27 | for (int i = 0; i < s.length() - 1; ++i) { 28 | if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CharactersSame.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class CharactersSame { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | assert isAllCharactersSame(""); 10 | assert !isAllCharactersSame("aab"); 11 | assert isAllCharactersSame("aaa"); 12 | assert isAllCharactersSame("11111"); 13 | } 14 | 15 | /** 16 | * check if all the characters of a string are same 17 | * 18 | * @param s the string to check 19 | * @return {@code true} if all characters of a string are same, otherwise 20 | * {@code false} 21 | */ 22 | public static boolean isAllCharactersSame(String s) { 23 | for (int i = 1, length = s.length(); i < length; ++i) { 24 | if (s.charAt(i) != s.charAt(0)) { 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CheckAnagrams.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Two strings are anagrams if they are made of the same letters arranged 8 | * differently (ignoring the case). 9 | */ 10 | public class CheckAnagrams { 11 | 12 | public static void main(String[] args) { 13 | assert isAnagrams("Silent", "Listen"); 14 | assert isAnagrams("This is a string", "Is this a string"); 15 | assert !isAnagrams("There", "Their"); 16 | } 17 | 18 | /** 19 | * Check if two strings are anagrams or not 20 | * 21 | * @param s1 the first string 22 | * @param s2 the second string 23 | * @return {@code true} if two string are anagrams, otherwise {@code false} 24 | */ 25 | public static boolean isAnagrams(String s1, String s2) { 26 | int l1 = s1.length(); 27 | int l2 = s2.length(); 28 | s1 = s1.toLowerCase(); 29 | s2 = s2.toLowerCase(); 30 | Map charAppearances = new HashMap<>(); 31 | 32 | for (int i = 0; i < l1; i++) { 33 | char c = s1.charAt(i); 34 | int numOfAppearances = charAppearances.getOrDefault(c, 0); 35 | charAppearances.put(c, numOfAppearances + 1); 36 | } 37 | 38 | for (int i = 0; i < l2; i++) { 39 | char c = s2.charAt(i); 40 | if (!charAppearances.containsKey(c)) { 41 | return false; 42 | } 43 | charAppearances.put(c, charAppearances.get(c) - 1); 44 | } 45 | 46 | for (int cnt : charAppearances.values()) { 47 | if (cnt != 0) { 48 | return false; 49 | } 50 | } 51 | return true; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CheckVowels.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Vowel Count is a system whereby character strings are placed in order based 5 | * on the position of the characters in the conventional ordering of an 6 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 7 | */ 8 | class CheckVowels { 9 | 10 | public static void main(String[] args) { 11 | assert !hasVowels("This is a strings"); 12 | assert hasVowels("Hello World"); 13 | assert hasVowels("Java is fun"); 14 | assert !hasVowels("123hi"); 15 | assert hasVowels("Coding vs Programming"); 16 | } 17 | 18 | /** 19 | * Check if a string is has vowels or not 20 | * 21 | * @param input a string 22 | * @return {@code true} if given string has vowels, otherwise {@code false} 23 | */ 24 | public static boolean hasVowels(String input) { 25 | if (input.matches("[AEIOUaeiou]")) { 26 | countVowels(input); 27 | return true; 28 | } 29 | return false; 30 | } 31 | 32 | /** 33 | * count the number of vowels 34 | * 35 | * @param input a string prints the count of vowels 36 | */ 37 | public static void countVowels(String input) { 38 | input = input.toLowerCase(); 39 | int count = 0; 40 | int i = 0; 41 | while (i < input.length()) { 42 | if (input.charAt(i) == 'a' 43 | || input.charAt(i) == 'e' 44 | || input.charAt(i) == 'i' 45 | || input.charAt(i) == 'o' 46 | || input.charAt(i) == 'u') { 47 | count++; 48 | } 49 | i++; 50 | } 51 | System.out.println(count); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | // Longest Palindromic Substring 4 | import java.util.Scanner; 5 | 6 | ; 7 | 8 | class LongestPalindromicSubstring { 9 | 10 | public static void main(String[] args) { 11 | Solution s = new Solution(); 12 | String str = ""; 13 | Scanner sc = new Scanner(System.in); 14 | System.out.print("Enter the string: "); 15 | str = sc.nextLine(); 16 | System.out.println("Longest substring is : " + s.longestPalindrome(str)); 17 | } 18 | } 19 | 20 | class Solution { 21 | 22 | public String longestPalindrome(String s) { 23 | if (s == null || s.length() == 0) { 24 | return ""; 25 | } 26 | int n = s.length(); 27 | String maxStr = ""; 28 | for (int i = 0; i < n; ++i) { 29 | for (int j = i; j < n; ++j) { 30 | if (isValid(s, i, j) == true) { 31 | if (j - i + 1 > maxStr.length()) { // update maxStr 32 | maxStr = s.substring(i, j + 1); 33 | } 34 | } 35 | } 36 | } 37 | return maxStr; 38 | } 39 | 40 | private boolean isValid(String s, int lo, int hi) { 41 | int n = hi - lo + 1; 42 | for (int i = 0; i < n / 2; ++i) { 43 | if (s.charAt(lo + i) != s.charAt(hi - i)) { 44 | return false; 45 | } 46 | } 47 | return true; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Lower.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class Lower { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 10 | for (String s : strings) { 11 | assert toLowerCase(s).equals(s.toLowerCase()); 12 | } 13 | } 14 | 15 | /** 16 | * Converts all of the characters in this {@code String} to lower case 17 | * 18 | * @param s the string to convert 19 | * @return the {@code String}, converted to lowercase. 20 | */ 21 | public static String toLowerCase(String s) { 22 | char[] values = s.toCharArray(); 23 | for (int i = 0; i < values.length; ++i) { 24 | if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { 25 | values[i] = Character.toLowerCase(values[i]); 26 | } 27 | } 28 | return new String(values); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Pangram.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Wikipedia: https://en.wikipedia.org/wiki/Pangram 5 | */ 6 | public class Pangram { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | assert isPangram("The quick brown fox jumps over the lazy dog"); 13 | assert !isPangram("The quick brown fox jumps over the azy dog"); 14 | /* not exists l character */ 15 | } 16 | 17 | /** 18 | * Check if a string is a pangram string or not 19 | * 20 | * @param s string to check 21 | * @return {@code true} if given string is pangram, otherwise {@code false} 22 | */ 23 | public static boolean isPangram(String s) { 24 | boolean[] marked = new boolean[26]; 25 | /* by default all letters don't exists */ 26 | char[] values = s.toCharArray(); 27 | for (char value : values) { 28 | if (Character.isLetter(value)) { 29 | int index = Character.isUpperCase(value) ? value - 'A' : value - 'a'; 30 | marked[index] = true; 31 | /* mark current character exists */ 32 | } 33 | } 34 | 35 | for (boolean b : marked) { 36 | if (!b) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Reverse String using different version 5 | */ 6 | public class ReverseString { 7 | 8 | public static void main(String[] args) { 9 | assert reverse("abc123").equals("321cba"); 10 | assert reverse2("abc123").equals("321cba"); 11 | } 12 | 13 | /** 14 | * easiest way to reverses the string str and returns it 15 | * 16 | * @param str string to be reversed 17 | * @return reversed string 18 | */ 19 | public static String reverse(String str) { 20 | return new StringBuilder(str).reverse().toString(); 21 | } 22 | 23 | /** 24 | * second way to reverses the string str and returns it 25 | * 26 | * @param str string to be reversed 27 | * @return reversed string 28 | */ 29 | public static String reverse2(String str) { 30 | 31 | if (str == null || str.isEmpty()) { 32 | return str; 33 | } 34 | 35 | char[] value = str.toCharArray(); 36 | for (int i = 0, j = str.length() - 1; i < j; i++, j--) { 37 | char temp = value[i]; 38 | value[i] = value[j]; 39 | value[j] = temp; 40 | } 41 | return new String(value); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Upper.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class Upper { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 10 | for (String s : strings) { 11 | assert toUpperCase(s).equals(s.toUpperCase()); 12 | } 13 | } 14 | 15 | /** 16 | * Converts all of the characters in this {@code String} to upper case 17 | * 18 | * @param s the string to convert 19 | * @return the {@code String}, converted to uppercase. 20 | */ 21 | public static String toUpperCase(String s) { 22 | char[] values = s.toCharArray(); 23 | for (int i = 0; i < values.length; ++i) { 24 | if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { 25 | values[i] = Character.toUpperCase(values[i]); 26 | } 27 | } 28 | return new String(values); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | public class KaprekarNumbersTest { 8 | 9 | @Test 10 | void testFor1() 11 | { 12 | assertTrue(KaprekarNumbers.isKaprekarNumber(1)); 13 | } 14 | 15 | @Test 16 | void testFor45() 17 | { 18 | assertTrue(KaprekarNumbers.isKaprekarNumber(45)); 19 | } 20 | 21 | @Test 22 | void testFor297() 23 | { 24 | assertTrue(KaprekarNumbers.isKaprekarNumber(297)); 25 | } 26 | 27 | @Test 28 | void testFor2223() 29 | { 30 | assertTrue(KaprekarNumbers.isKaprekarNumber(2223)); 31 | } 32 | 33 | @Test 34 | void testFor857143() 35 | { 36 | assertTrue(KaprekarNumbers.isKaprekarNumber(857143)); 37 | } 38 | 39 | 40 | @Test 41 | void testFor3() 42 | { 43 | assertFalse(KaprekarNumbers.isKaprekarNumber(3)); 44 | } 45 | 46 | @Test 47 | void testFor26() 48 | { 49 | assertFalse(KaprekarNumbers.isKaprekarNumber(26)); 50 | } 51 | 52 | @Test 53 | void testFor98() 54 | { 55 | assertFalse(KaprekarNumbers.isKaprekarNumber(98)); 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PascalTriangleTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class PascalTriangleTest { 8 | 9 | @Test 10 | void testForOne() { 11 | int[][] result = PascalTriangle.pascal(1); 12 | int[][] expected = {{1}}; 13 | assertArrayEquals(result, expected); 14 | } 15 | 16 | @Test 17 | void testForTwo() { 18 | int[][] result = PascalTriangle.pascal(2); 19 | int[][] expected = {{1, 0}, {1, 1}}; 20 | assertArrayEquals(result, expected); 21 | } 22 | 23 | @Test 24 | void testForFive() { 25 | int[][] result = PascalTriangle.pascal(5); 26 | int[][] expected = {{1, 0, 0, 0, 0}, 27 | {1, 1, 0, 0, 0}, 28 | {1, 2, 1, 0, 0}, 29 | {1, 3, 3, 1, 0}, 30 | {1, 4, 6, 4, 1} 31 | }; 32 | assertArrayEquals(result, expected); 33 | } 34 | 35 | @Test 36 | void testForEight() { 37 | int[][] result = PascalTriangle.pascal(8); 38 | int[][] expected = {{1, 0, 0, 0, 0, 0, 0, 0}, 39 | {1, 1, 0, 0, 0, 0, 0, 0}, 40 | {1, 2, 1, 0, 0, 0, 0, 0}, 41 | {1, 3, 3, 1, 0, 0, 0, 0}, 42 | {1, 4, 6, 4, 1, 0, 0, 0}, 43 | {1, 5, 10, 10, 5, 1, 0, 0}, 44 | {1, 6, 15, 20, 15, 6, 1, 0}, 45 | {1, 7, 21, 35, 35, 21, 7, 1} 46 | }; 47 | assertArrayEquals(expected, result); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PronicNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | public class PronicNumberTest { 8 | 9 | @Test 10 | void testForPronicNumber() { 11 | 12 | //given 13 | int number = 30; 14 | 15 | //when 16 | boolean result = PronicNumber.isPronic(number); 17 | 18 | //then 19 | assertTrue(result); 20 | } 21 | 22 | @Test 23 | void testForNonPronicNumber() { 24 | 25 | //given 26 | int number = 21; 27 | 28 | //when 29 | boolean result = PronicNumber.isPronic(number); 30 | 31 | //then 32 | assertFalse(result); 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ArrayLeftRotationTest { 8 | 9 | @Test 10 | void testForOneElement() { 11 | int[] arr = {3}; 12 | int[] result = ArrayLeftRotation.rotateLeft(arr, 3); 13 | assertArrayEquals(arr, result); 14 | } 15 | 16 | @Test 17 | void testForZeroStep() { 18 | int[] arr = {3, 1, 5, 8, 6}; 19 | int[] result = ArrayLeftRotation.rotateLeft(arr, 0); 20 | assertArrayEquals(arr, result); 21 | } 22 | 23 | @Test 24 | void testForEqualSizeStep() { 25 | int[] arr = {3, 1, 5, 8, 6}; 26 | int[] result = ArrayLeftRotation.rotateLeft(arr, 5); 27 | assertArrayEquals(arr, result); 28 | } 29 | 30 | @Test 31 | void testForLowerSizeStep() { 32 | int[] arr = {3, 1, 5, 8, 6}; 33 | int n = 2; 34 | int[] expected = {5, 8, 6, 3, 1}; 35 | int[] result = ArrayLeftRotation.rotateLeft(arr, n); 36 | assertArrayEquals(expected, result); 37 | } 38 | 39 | @Test 40 | void testForHigherSizeStep() { 41 | int[] arr = {3, 1, 5, 8, 6}; 42 | int n = 7; 43 | int[] expected = {5, 8, 6, 3, 1}; 44 | int[] result = ArrayLeftRotation.rotateLeft(arr, n); 45 | assertArrayEquals(expected, result); 46 | } 47 | 48 | } --------------------------------------------------------------------------------