From 461af07d357f29bc9814607f6e8737a8bdaeff4b Mon Sep 17 00:00:00 2001 From: mohbius Date: Tue, 2 Oct 2018 13:40:12 +0530 Subject: [PATCH 01/46] Create Nth_fibonacci_using_goldenratio.java --- math/Nth_fibonacci_using_goldenratio.java | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 math/Nth_fibonacci_using_goldenratio.java diff --git a/math/Nth_fibonacci_using_goldenratio.java b/math/Nth_fibonacci_using_goldenratio.java new file mode 100644 index 0000000..1f29c54 --- /dev/null +++ b/math/Nth_fibonacci_using_goldenratio.java @@ -0,0 +1,39 @@ +// Java program to find n-th Fibonacci number +// Adapted from code by Anant Agarwal. +class Nth_fibonacci_using_goldenratio +{ + // Approximate value of golden ratio + static double PHI = 1.6180339; + + // Fibonacci numbers upto n = 5 + static int f[] = { 0, 1, 1, 2, 3, 5 }; + + // Function to find nth + // Fibonacci number + static int fib (int n) + { + // Fibonacci numbers for n < 6 + if (n < 6) + return f[n]; + + // Else start counting from + // 5th term + int t = 5; + int fn = 5; + + while (t < n) { + fn = (int)Math.round(fn * PHI); + t++; + } + + return fn; + } + + public static void main (String[] args) + { + int fibNo; + fibNo = fib(9); //RETURNS 34 + fibNo = fib(8); //RETURNS 21 + fibNo = fib(7); //RETURNS 13 + } +} From 843f4ecc26d49984f1520d1831d5f657419a175b Mon Sep 17 00:00:00 2001 From: Aniruddha Dave Date: Tue, 2 Oct 2018 18:21:41 +0530 Subject: [PATCH 02/46] Add HeapSort Implementation --- sorting/HeapSort.java | 80 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 sorting/HeapSort.java diff --git a/sorting/HeapSort.java b/sorting/HeapSort.java new file mode 100644 index 0000000..01cac34 --- /dev/null +++ b/sorting/HeapSort.java @@ -0,0 +1,80 @@ +/* + Heap Sort + Implementation of Heap Sort in Java which uses max heap +*/ + +public class HeapSort +{ + public void sort(int arr[]) + { + int n = arr.length; + + // Step 1: Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // Step 2: Extract elements one by one from heap + for (int i=n-1; i>=0; i--) + { + // Step 2.1: Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // Step 2.2: Call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + /* Method to heapify a subtree rooted with node i which is + + an index in arr[]. + Heap Size = n + */ + void heapify(int arr[], int n, int i) + { + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i Date: Thu, 1 Oct 2020 16:12:40 +0530 Subject: [PATCH 03/46] added HeapSort --- sorting/HeapSort.java | 74 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 sorting/HeapSort.java diff --git a/sorting/HeapSort.java b/sorting/HeapSort.java new file mode 100644 index 0000000..a647c88 --- /dev/null +++ b/sorting/HeapSort.java @@ -0,0 +1,74 @@ +// Java program for implementation of Heap Sort +public class HeapSort +{ + public void sort(int arr[]) + { + int n = arr.length; + + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i=n-1; i>0; i--) + { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + // To heapify a subtree rooted with node i which is + // an index in arr[]. n is size of heap + void heapify(int arr[], int n, int i) + { + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i Date: Fri, 2 Oct 2020 02:09:52 -0400 Subject: [PATCH 04/46] refactofing! --- .editorconfig | 13 - .github/code-of-conduct.md | 40 ++ .github/contributing.md | 3 + .github/issue-template.md | 1 + .github/pull-request-template.md | 6 + .gitignore | 7 - .travis.yml | 14 - .../backtracking}/CrosswordPuzzle.java | 0 .../ciphers}/Ceasercipher.java | 0 .../DoubleLinkedListOfInteger.java | 0 .../data-structures}/LinkedList.java | 0 .../data-structures}/SegmentTree.java | 0 .../data-structures}/Stack.java | 0 .../data-structures}/UseStack.java | 0 .../dynamic-programming}/EDIST.java | 0 .../dynamic-programming}/Kadane.java | 0 .../dynamic-programming}/Knapsack.java | 0 .../LongestCommonSubsequence.java | 0 .../dynamic-programming}/MinCoinChange.java | 0 .../MinEditsToConvertStr1ToStr2.java | 0 .../dynamic-programming}/fibonacci.java | 0 {graph => algorithms/graph}/BinaryTree.java | 0 {graphs => algorithms/graphs}/BFS.java | 0 .../graphs}/TopologicalSort.java | 0 {math => algorithms/math}/MatrixMultiply.java | 0 .../searches}/BinarySearch.java | 0 .../searches}/InterpolationSearch.java | 0 .../searches}/LinearSearch.java | 0 .../sorting}/BubbleSort.java | 0 .../sorting}/CountingSort.java | 0 .../sorting}/InsertionSort.java | 0 .../sorting}/MergeSort.java | 0 .../sorting}/QuickSort.java | 0 .../sorting}/SelectionSort.java | 0 .../sorting}/ShellSort.java | 0 license | 2 +- readme.md | 470 ++++++++++++++---- scripts/formatter.js | 151 ------ scripts/package.json | 17 - scripts/validate.js | 42 -- src/.gitkeep | 0 41 files changed, 428 insertions(+), 338 deletions(-) delete mode 100644 .editorconfig create mode 100644 .github/code-of-conduct.md create mode 100644 .github/contributing.md create mode 100644 .github/issue-template.md create mode 100644 .github/pull-request-template.md delete mode 100644 .gitignore delete mode 100644 .travis.yml rename {backtracking => algorithms/backtracking}/CrosswordPuzzle.java (100%) rename {ciphers => algorithms/ciphers}/Ceasercipher.java (100%) rename {data-structures => algorithms/data-structures}/DoubleLinkedListOfInteger.java (100%) rename {data-structures => algorithms/data-structures}/LinkedList.java (100%) rename {data-structures => algorithms/data-structures}/SegmentTree.java (100%) rename {data-structures => algorithms/data-structures}/Stack.java (100%) rename {data-structures => algorithms/data-structures}/UseStack.java (100%) rename {dynamic-programming => algorithms/dynamic-programming}/EDIST.java (100%) rename {dynamic-programming => algorithms/dynamic-programming}/Kadane.java (100%) rename {dynamic-programming => algorithms/dynamic-programming}/Knapsack.java (100%) rename {dynamic-programming => algorithms/dynamic-programming}/LongestCommonSubsequence.java (100%) rename {dynamic-programming => algorithms/dynamic-programming}/MinCoinChange.java (100%) rename {dynamic-programming => algorithms/dynamic-programming}/MinEditsToConvertStr1ToStr2.java (100%) rename {dynamic-programming => algorithms/dynamic-programming}/fibonacci.java (100%) rename {graph => algorithms/graph}/BinaryTree.java (100%) rename {graphs => algorithms/graphs}/BFS.java (100%) rename {graphs => algorithms/graphs}/TopologicalSort.java (100%) rename {math => algorithms/math}/MatrixMultiply.java (100%) rename {searches => algorithms/searches}/BinarySearch.java (100%) rename {searches => algorithms/searches}/InterpolationSearch.java (100%) rename {searches => algorithms/searches}/LinearSearch.java (100%) rename {sorting => algorithms/sorting}/BubbleSort.java (100%) rename {sorting => algorithms/sorting}/CountingSort.java (100%) rename {sorting => algorithms/sorting}/InsertionSort.java (100%) rename {sorting => algorithms/sorting}/MergeSort.java (100%) rename {sorting => algorithms/sorting}/QuickSort.java (100%) rename {sorting => algorithms/sorting}/SelectionSort.java (100%) rename {sorting => algorithms/sorting}/ShellSort.java (100%) delete mode 100644 scripts/formatter.js delete mode 100644 scripts/package.json delete mode 100644 scripts/validate.js create mode 100644 src/.gitkeep diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 2f59d86..0000000 --- a/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = space -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.yml] -indent_style = space -indent_size = 2 diff --git a/.github/code-of-conduct.md b/.github/code-of-conduct.md new file mode 100644 index 0000000..f809c8b --- /dev/null +++ b/.github/code-of-conduct.md @@ -0,0 +1,40 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/.github/contributing.md b/.github/contributing.md new file mode 100644 index 0000000..01f6600 --- /dev/null +++ b/.github/contributing.md @@ -0,0 +1,3 @@ +## Contributing + +> Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. \ No newline at end of file diff --git a/.github/issue-template.md b/.github/issue-template.md new file mode 100644 index 0000000..99764fe --- /dev/null +++ b/.github/issue-template.md @@ -0,0 +1 @@ +I am creating an issue because... diff --git a/.github/pull-request-template.md b/.github/pull-request-template.md new file mode 100644 index 0000000..3bc0935 --- /dev/null +++ b/.github/pull-request-template.md @@ -0,0 +1,6 @@ +I am creating a pull request for... + +- [ ] New algorithm +- [ ] Update to an algorithm +- [ ] Fix an error +- [ ] Other - *Describe below* \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 6253c15..0000000 --- a/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -DS_Store -*.o - -/scripts/node_modules -/scripts/yarn.lock -/scripts/package-lock.json -.vscode/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e28aa71..0000000 --- a/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: node_js -node_js: - - '9' - -before_script: - - npm version - - cd scripts/ - - npm install - -script: - - npm run validate - -notifications: - email: false diff --git a/backtracking/CrosswordPuzzle.java b/algorithms/backtracking/CrosswordPuzzle.java similarity index 100% rename from backtracking/CrosswordPuzzle.java rename to algorithms/backtracking/CrosswordPuzzle.java diff --git a/ciphers/Ceasercipher.java b/algorithms/ciphers/Ceasercipher.java similarity index 100% rename from ciphers/Ceasercipher.java rename to algorithms/ciphers/Ceasercipher.java diff --git a/data-structures/DoubleLinkedListOfInteger.java b/algorithms/data-structures/DoubleLinkedListOfInteger.java similarity index 100% rename from data-structures/DoubleLinkedListOfInteger.java rename to algorithms/data-structures/DoubleLinkedListOfInteger.java diff --git a/data-structures/LinkedList.java b/algorithms/data-structures/LinkedList.java similarity index 100% rename from data-structures/LinkedList.java rename to algorithms/data-structures/LinkedList.java diff --git a/data-structures/SegmentTree.java b/algorithms/data-structures/SegmentTree.java similarity index 100% rename from data-structures/SegmentTree.java rename to algorithms/data-structures/SegmentTree.java diff --git a/data-structures/Stack.java b/algorithms/data-structures/Stack.java similarity index 100% rename from data-structures/Stack.java rename to algorithms/data-structures/Stack.java diff --git a/data-structures/UseStack.java b/algorithms/data-structures/UseStack.java similarity index 100% rename from data-structures/UseStack.java rename to algorithms/data-structures/UseStack.java diff --git a/dynamic-programming/EDIST.java b/algorithms/dynamic-programming/EDIST.java similarity index 100% rename from dynamic-programming/EDIST.java rename to algorithms/dynamic-programming/EDIST.java diff --git a/dynamic-programming/Kadane.java b/algorithms/dynamic-programming/Kadane.java similarity index 100% rename from dynamic-programming/Kadane.java rename to algorithms/dynamic-programming/Kadane.java diff --git a/dynamic-programming/Knapsack.java b/algorithms/dynamic-programming/Knapsack.java similarity index 100% rename from dynamic-programming/Knapsack.java rename to algorithms/dynamic-programming/Knapsack.java diff --git a/dynamic-programming/LongestCommonSubsequence.java b/algorithms/dynamic-programming/LongestCommonSubsequence.java similarity index 100% rename from dynamic-programming/LongestCommonSubsequence.java rename to algorithms/dynamic-programming/LongestCommonSubsequence.java diff --git a/dynamic-programming/MinCoinChange.java b/algorithms/dynamic-programming/MinCoinChange.java similarity index 100% rename from dynamic-programming/MinCoinChange.java rename to algorithms/dynamic-programming/MinCoinChange.java diff --git a/dynamic-programming/MinEditsToConvertStr1ToStr2.java b/algorithms/dynamic-programming/MinEditsToConvertStr1ToStr2.java similarity index 100% rename from dynamic-programming/MinEditsToConvertStr1ToStr2.java rename to algorithms/dynamic-programming/MinEditsToConvertStr1ToStr2.java diff --git a/dynamic-programming/fibonacci.java b/algorithms/dynamic-programming/fibonacci.java similarity index 100% rename from dynamic-programming/fibonacci.java rename to algorithms/dynamic-programming/fibonacci.java diff --git a/graph/BinaryTree.java b/algorithms/graph/BinaryTree.java similarity index 100% rename from graph/BinaryTree.java rename to algorithms/graph/BinaryTree.java diff --git a/graphs/BFS.java b/algorithms/graphs/BFS.java similarity index 100% rename from graphs/BFS.java rename to algorithms/graphs/BFS.java diff --git a/graphs/TopologicalSort.java b/algorithms/graphs/TopologicalSort.java similarity index 100% rename from graphs/TopologicalSort.java rename to algorithms/graphs/TopologicalSort.java diff --git a/math/MatrixMultiply.java b/algorithms/math/MatrixMultiply.java similarity index 100% rename from math/MatrixMultiply.java rename to algorithms/math/MatrixMultiply.java diff --git a/searches/BinarySearch.java b/algorithms/searches/BinarySearch.java similarity index 100% rename from searches/BinarySearch.java rename to algorithms/searches/BinarySearch.java diff --git a/searches/InterpolationSearch.java b/algorithms/searches/InterpolationSearch.java similarity index 100% rename from searches/InterpolationSearch.java rename to algorithms/searches/InterpolationSearch.java diff --git a/searches/LinearSearch.java b/algorithms/searches/LinearSearch.java similarity index 100% rename from searches/LinearSearch.java rename to algorithms/searches/LinearSearch.java diff --git a/sorting/BubbleSort.java b/algorithms/sorting/BubbleSort.java similarity index 100% rename from sorting/BubbleSort.java rename to algorithms/sorting/BubbleSort.java diff --git a/sorting/CountingSort.java b/algorithms/sorting/CountingSort.java similarity index 100% rename from sorting/CountingSort.java rename to algorithms/sorting/CountingSort.java diff --git a/sorting/InsertionSort.java b/algorithms/sorting/InsertionSort.java similarity index 100% rename from sorting/InsertionSort.java rename to algorithms/sorting/InsertionSort.java diff --git a/sorting/MergeSort.java b/algorithms/sorting/MergeSort.java similarity index 100% rename from sorting/MergeSort.java rename to algorithms/sorting/MergeSort.java diff --git a/sorting/QuickSort.java b/algorithms/sorting/QuickSort.java similarity index 100% rename from sorting/QuickSort.java rename to algorithms/sorting/QuickSort.java diff --git a/sorting/SelectionSort.java b/algorithms/sorting/SelectionSort.java similarity index 100% rename from sorting/SelectionSort.java rename to algorithms/sorting/SelectionSort.java diff --git a/sorting/ShellSort.java b/algorithms/sorting/ShellSort.java similarity index 100% rename from sorting/ShellSort.java rename to algorithms/sorting/ShellSort.java diff --git a/license b/license index 6f8bf2d..559a12b 100644 --- a/license +++ b/license @@ -1,7 +1,7 @@ MIT License Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.com) -Copyright (c) 2018 Abraham Hernandez (abranhe.com) +Copyright (c) 2018 Carlos Abraham (abranhe.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/readme.md b/readme.md index 6c00484..dd64172 100644 --- a/readme.md +++ b/readme.md @@ -1,132 +1,416 @@ +We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) + +
+
+
+
+
+ Algorithms Logo +
+
+
+
+
+
+ +

+ What is an algorithm?    + Contributing    + Stickers & T-Shirts +

+ + +

+ + Twitter +    + + Instagram +    + + Github +    +

- -
-
-
-
-
- -
-
-
-
-
-
-
+

+ Huge collection of All ▲lgorithms implemented in multiple languages +


-

All ▲lgorithms implemented in Java

- - + + + - - -
-
-allalgorithms.com +
- +## See -## Contents +- [What is an algorithm](#what-is-an-algorithm) +- [Contributing](https://github.com/AllAlgorithms/algorithms/blob/master/.github/contributing.md) +- [Code of Conduct](https://github.com/AllAlgorithms/algorithms/blob/master/.github/code-of-conduct.md) +- [Stickers and T-Shirts](https://www.redbubble.com/people/abranhe/works/34285088) +- [Twitter](https://twitter.com/AllAlgorithms) +- [Instagram](https://instagram.com/AllAlgorithms) +- [Algorithms Categories](#categories) +- [Maintainers](#maintainers) +- [License](#license) -You can find the All ▲lgorithms categories at [algorithms.com/categories](https://algorithms.com/categories) - - [Artificial intelligence](#artificial-intelligence) - - [Backtracking](#backtracking) - - [Bit manipulation](#bit-manipulation) - - [Cellular automaton](#cellular-automaton) - - [Computational geometry](#computational-geometry) - - [Cryptography](#cryptography) - - [Data structures](#data-structures) - - [Divide and conquer](#divide-and-conquer) - - [Dynamic programming](#dynamic-programming) - - [Gaming theory](#gaming-theory) - - [Graphs](#graphs) - - [Greedy algorithms](#greedy-algorithms) - - [Math](#math) - - [Networking](#networking) - - [Numerical analysis](#numerical-analysis) - - [Online challenges](#online-challenges) - - [Randomized algorithms](#randomized-algorithms) - - [Serches](#serches) - - [Selections](#selections) - - [Sorting](#sorting) - - [Strings](#strings) - - [No category](#no-category) +## What is an algorithm? -## Backtracking +Informally, an algorithm is any well-defined computational procedure that takes +some value, or set of values, as input and produces some value, or set of values, as +output. An algorithm is thus a sequence of computational steps that transform the +input into the output. - - [Crossword Puzzle](backtracking/CrosswordPuzzle.java) +An algorithm should have three important characteristics to be considered valid: -## Ciphers +- **It should be finite**: If your algorithm never ends trying to solve the problem +it was designed to solve then it is useless +- **It should have well defined instructions**: Each step of the algorithm has to +be precisely defined; the instructions should be unambiguously specified for each case. +- **It should be effective**: The algorithm should solve the problem it was designed +to solve. And it should be possible to demonstrate that the algorithm converges with +just a paper and pencil. - - [Ceasercipher](ciphers/Ceasercipher.java) +## Categories -## Data structures +> Structure of The All ▲lgoritms project - - [Double Linked List Of Integer](data-structures/DoubleLinkedListOfInteger.java) - - [Linked List](data-structures/LinkedList.java) - - [Segment Tree](data-structures/SegmentTree.java) - - [Stack](data-structures/Stack.java) - - [Use Stack](data-structures/UseStack.java) +- [Artificial Intelligence](#artificial-intelligence) +- [Backtracking](#backtracking) +- [Bit Manipulation](#bit-manipulation) +- [Cellular Automaton](#cellular-automaton) +- [Ciphers](#ciphers) +- [Computational Geometry](#computational-geometry) +- [Cryptography](#cryptography) +- [Data Structures](#data-structures) +- [Divide and conquer](#divide-and-conquer) +- [Dynamic Programming](#dynamic-programming) +- [Gaming Theory](#gaming-theory) +- [Graphs](#graphs) +- [Greedy Algorithms](#greedy-algorithms) +- [Math](#math) +- [Networking](#networking) +- [Numerical Analysis](#numerical-analysis) +- [Operating system](#operating-system) +- [Randomized Algorithms](#randomized-algorithms) +- [Searches](#searches) +- [Selections Algorithms](#selections-algorithms) +- [Sorting](#sorting) +- [Strings](#strings) +- [Online Challenges](#online-challenges) +- [Others](#others) -## Dynamic programming +## [Artificial Intelligence](artificial-intelligence) - - [Edist](dynamic-programming/Edist.java) - - [Fibonacci](dynamic-programming/Fibonacci.java) - - [Kadane](dynamic-programming/Kadane.java) - - [Knapsack](dynamic-programming/Knapsack.java) - - [Longest Common Subsequence](dynamic-programming/LongestCommonSubsequence.java) - - [Min Coin Change](dynamic-programming/MinCoinChange.java) - - [Min Edits To Convert Str1 To Str2](dynamic-programming/MinEditsToConvertStr1ToStr2.java) +- [Density-based spatial clustering of applications with noise (DBSCAN Clustering)](https://allalgorithms.com/docs/dbscan) +- [Interactive Self-Organizing Data Analysis Technique yAy! (ISODATA Clustering)](https://allalgorithms.com/docs/isodata) +- [Linear Regression](https://allalgorithms.com/docs/linear-regression) +- [Logistic Regression](https://allalgorithms.com/docs/logistic-regression) +- [Neutral Style Transfer](https://allalgorithms.com/docs/neutral-style-transfer) +- [SATisfiable (SAT)](https://allalgorithms.com/docs/sat) +- [Travelling salesman problem (TSP)](https://allalgorithms.com/docs/tsp) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) +- [Artificial Neutral Network](https://allalgorithms.com/docs/artificial-neutral-network) +- [Convolutional Neutral Network](https://allalgorithms.com/docs/convolutional-neutral-network) +- [Decision Tree](https://allalgorithms.com/docs/decision-tree) +- [Factorization Machines](https://allalgorithms.com/docs/factorization-machines) +- [Gaussian Mixture Model](https://allalgorithms.com/docs/gaussian-mixtrue-model) +- [Gradient Boosting Trees](https://allalgorithms.com/docs/gradient-boostring-trees) +- [Hierachical Clustering](https://allalgorithms.com/docs/hierachical-clustering) +- [Image Processing](https://allalgorithms.com/docs/image-processing) +- [K Nearest Neighbors](https://allalgorithms.com/docs/k-nearest-neighbors) +- [K Means](https://allalgorithms.com/docs/k-means) +- [Minimax](https://allalgorithms.com/docs/minimax) +- [Native Bayes](https://allalgorithms.com/docs/native-bayes) +- [Nearest Sequence Memory](https://allalgorithms.com/docs/nearest-sequence-memory) +- [Neutral Network](https://allalgorithms.com/docs/neutral-network) +- [Perceptron](https://allalgorithms.com/docs/perceptron) +- [Principal Component Analysis](https://allalgorithms.com/docs/principal-component-analysis) +- [Q Learing](https://allalgorithms.com/docs/q-learning) +- [Random Forests](https://allalgorithms.com/docs/random-forest) +- [Restricted Boltzman Machine](https://allalgorithms.com/docs/restricted-boltzman-machine) -## Graph +## [Backtracking](backtracking) - - [Binary Tree](graph/BinaryTree.java) +- [Algorithm X](backtracking/algorithm-x) +- [Crossword Puzzle](backtracking/crossword-Puzzle) +- [Knight Tour](backtracking/knight-tour) +- [M Coloring Problem](backtracking/m-coloring-problem) +- [N Queen](backtracking/n-queen) +- [Number of ways in Maze](backtracking/number-of-ways-in-maze) +- [Partitions of set](backtracking/partitions-of-set) +- [Permutation of Strings](backtracking/permutation-of-strings) +- [Powerset](backtracking/powerset) +- [Rat in maze](backtracking/rat-in-maze) +- [Subset Sum](backtracking/subset-sum) +- [Sudoku Solve](backtracking/sudoku-solve) -## Graphs +## [Bit Manipulation](bit-manipulation) - - [Bfs](graphs/Bfs.java) - - [Topological Sort](graphs/TopologicalSort.java) +- [Addition using bits](bit-manipulation/adding-using-bits) +- [Bit divisor](bit-manipulation/bit-divisor) +- [Byte swapper](bit-manipulation/byte-swapper) +- [Convert numbers to binary](bit-manipulation/convert-numbers-to-binary) +- [Count set bits](bit-manipulation/count-set-bits) +- [Flip bits](bit-manipulation/flip-bits) +- [Hamming distance](bit-manipulation/hamming-distace) +- [Invert bit](bit-manipulation/invert-bit) +- [Lonely integer](bit-manipulation/lonely-integer) +- [Magic Number](bit-manipulation/magic-number) +- [Maximum XOR Value](bit-manipulation/maximun-xor-value) +- [Power of 2](bit-manipulation/power-of-2) +- [Subset Generation](bit-manipulation/subset-generation) +- [Sum binary numbers](bit-manipulation/sum-binary-numbers) +- [Sum equals XOR](bit-manipulation/sum-equals-xor) +- [Thrice unique number](bit-manipulation/thrice-unique-number) +- [Twice unique number](bit-manipulation/twice-unique-number) +- [XOR Swap](bit-manipulation/xor-swap) -## Math +## [Cellular Automaton](cellular-automaton) - - [Matrix Multiply](math/MatrixMultiply.java) +- [Brians Brain](cellular-automaton/brians-brain) +- [Conways Game of life](cellular-automaton/conways-game-of-life) +- [Elementary Cellular Automata](cellular-automaton/elementary-cellular-automata) +- [Generic Algorithm](cellular-automaton/generic-algorithm) +- [Langtons Ant](cellular-automaton/langtons-ant) +- [Nobili Cellular Automata](cellular-automaton/nobili-cellular-automata) +- [Von Neoumann Cellular Automata](cellular-automaton/von-neoumann-cellular-automata) -## Searches +## [Computational Geometry](computational-geometry) - - [Binary Search](searches/BinarySearch.java) - - [Interpolation Search](searches/InterpolationSearch.java) - - [Linear Search](searches/LinearSearch.java) +- [2D Line intersection](computational-geometry/) +- [2D Separating Axis test](computational-geometry/) +- [Area of polygon](computational-geometry/) +- [Area of triangle](computational-geometry/) +- [Axis aligned bounding box collision](computational-geometry/) +- [Bresenham Line](computational-geometry/) +- [Chans Algorithm](computational-geometry/) +- [Cohen Sutherland Lineclip](computational-geometry/) +- [Distance between points](computational-geometry/) +- [Graham Scan](computational-geometry/) +- [Halfplane intersection](computational-geometry/) +- [Jarvis March](computational-geometry/) +- [Quickull](computational-geometry/) +- [Sphere tetrahedron intersection](computational-geometry/) +- [Sutherland Hodgeman clipping](computational-geometry/) -## Sorting +## [Cryptography](cryptography) - - [Bubble Sort](sorting/BubbleSort.java) - - [Counting Sort](sorting/CountingSort.java) - - [Insertion Sort](sorting/InsertionSort.java) - - [Merge Sort](sorting/MergeSort.java) - - [Quick Sort](sorting/QuickSort.java) - - [Selection Sort](sorting/SelectionSort.java) - - [Shell Sort](sorting/ShellSort.java) +- [Affine Cipher](cryptography/) +- [Atbash Cipher](cryptography/) +- [Autokey Cipher](cryptography/) +- [Baconian Cipher](cryptography/) +- [Caesar Cipher](cryptography/) +- [Colummnar Cipher](cryptography/) +- [Vigenere Cipher](cryptography/) - +## [Data Structures](data-structures) -## License +- [Bag](data-structures/bag/) +- [Hashes](data-structures/hashes/) +- [Linked List](data-structures/linked-list/) +- [List](data-structures/list/) +- [Queue](data-structures/queue/) +- [Stack](data-structures/stack/) +- [Tree](data-structures/tree/) + +## [Divide and conquer](divide-and-conquer) + +- [Strassen Matrix Manipulation](divide-and-conquer/) +- [Closest Pair of Point](divide-and-conquer/) +- [Inversion Count](divide-and-conquer/) +- [Karatsuba Multiplication](divide-and-conquer/) +- [Maximum Contiguous subsequence sum](divide-and-conquer/) +- [Merge Sort using divide and conquer](divide-and-conquer/) +- [Quick Sort using divide and conquer](divide-and-conquer/) +- [Tournament Method to find min max](divide-and-conquer/) +- [Warnock Algorithm](divide-and-conquer/) +- [X Power Y](divide-and-conquer/) + +## [Dynamic Programming](dynamic-programming) + +- [Array Median](dynamic-programming) +- [Optima Binary Search Tree](dynamic-programming) +- [Binomial Coefficient](dynamic-programming) + +## [Gaming Theory](gaming-theory) + +- [Nim Next Best Move Game](gaming-theory/) +- [Nim Win Loss Game](gaming-theory/) +- [Grundy Numbers Kayle Game](gaming-theory/) + +## [Graphs](graphs) + +- [Bipartite Check](graphs/) +- [Adjacency Lists graphs representation](graphs/) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) -This work is released under [MIT License][MIT] +## [Greedy Algorithms](greedy-algorithms) -[![MIT IMG][MIT-logo]][MIT] +- [Activity Selection](greedy-algorithms) +- [Dijkstra Shortest Path](greedy-algorithms) +- [Egyptian Fraction](greedy-algorithms) -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. +## [Math](math) + +- [2 Sum](math/) +- [Add Polynomials](math/) +- [Amicable Numbers](math/) +- [Armstrong Numbers](math/) +- [Automorphic Numbers](math/) +- [Average Stream Numbers](math/) +- [Babylonian Method](math/) +- [Binomial Coefficient](math/) +- [Catalan Number](math/) +- [Check is Square](math/) +- [Convolution](math/) +- [Coprime Numbers](math/) +- [Count Digits](math/) +- [Count Trailing Zeroes](math/) +- [Decoding of String](math/) +- [Delannoy Number](math/) +- [Derangements](math/) +- [DFA Division](math/) +- [Diophantine](math/) +- [Divided Differences](math/) +- [Euler Totient](math/) +- [Exponentiation Power](math/) +- [Factorial](math/factorial) +- [Fast Fourier transform](math/) +- [Fast inverse (sqrt) Square Root](math/) + +## [Networking](networking) + +- [Packet Sniffer](networking/) +- [Determine Endianess](networking/) +- [Validate IP](networking/) + +## [Numerical Analysis](numerical-analysis) + +- [Integral](numerical-analysis/integral) +- [Monte Carlo](numerical-analysis/monte-carlo) +- [Runge Kutt](numerical-analysis/runge-kutt) + +## [Operating system](operating-system) + +- [Currency](operating-system/) +- [Deadlocks](operating-system/) +- [Memory Management](operating-system/) +- [Scheduling](operating-system/) +- [Shell](operating-system/) + +## [Randomized Algorithms](randomized-algorithms) + +- [Birthday Paradox](randomized-algorithms) +- [Karger Minimum Cut Algorithm](randomized-algorithms) +- [Kth Smallest Element Algorithm](randomized-algorithms) +- [Random from Stream](randomized-algorithms) +- [Random Node Linked list](randomized-algorithms) +- [Randomized Quicksort](randomized-algorithms) +- [Reservoir Sampling](randomized-algorithms) +- [Shuffle an Array](randomized-algorithms) + +## [Searches](searches) + +- [Binary Search](searches) +- [Exponential Search](searches) +- [Fibonacci Search](searches) +- [Fuzzy Search](searches) +- [Interpolation Search](searches) +- [Jump Search](searches) +- [Linear Search](searches) +- [Ternay Search](searches) + +## [Selections Algorithms](selections-algorithms) + +- [Median of Medians](selections-algorithms) +- [Quick Select](selections-algorithms) + +## [Sorting](sorting) + +- [Bead Sort](sorting/) +- [Bogo Sort](sorting/) +- [Bubble Sort](sorting/) +- [Bucket Sort](sorting/) +- [Circle Sort](sorting/) +- [Comb Sort](sorting/) +- [Counting Sort](sorting/) +- [Cycle Sort](sorting/) +- [Flash Sort](sorting/) +- [Gnome Sort](sorting/) +- [Heap Sort](sorting/) +- [Insertion Sort](sorting/) +- [Intro Sort](sorting/) +- [Median Sort](sorting/) +- [Merge Sort](sorting/) +- [Pipeonhole Sort](sorting/) +- [Quick Sort](sorting/) +- [Radix Sort](sorting/) +- [Selection Sort](sorting/) +- [Shaker Sort](sorting/) +- [Shell Sort](sorting/) +- [Sleep Sort](sorting/) +- [Stooge Sort](sorting/) +- [Topological Sort](sorting/) +- [Tree Sort](sorting/) + +## [Strings](strings) + +- [Aho Corasick Algorithm](strings) +- [Anagram Search](strings) +- [Arithmetic on large numbers](strings) +- [Boyer Moore Algorithm](strings) +- [Finite Automata](strings) +- [Kasai Algorithm](strings) +- [Kmp Algorithm](strings) +- [Levenshteing Distance](strings) +- [Lipogram Checker](strings) + +## [Online Challenges](online-challenges) + +- [Coderbyte](online-challenges/coderbyte) +- [Code Chef](online-challenges/code-chef) +- [Code Eval](online-challenges/code-eval) +- [Hackerearth](online-challenges/hackerearth) +- [Hackerrank](online-challenges/hackerrank) +- [LeetCode](online-challenges/leetcode) +- [Project Euler](online-challenges/project-euler) +- [Rosalind](online-challenges/rosalind) +- [SPOJ](online-challenges/spoj) +- [Top Coder](online-challenges/top-coder)` + +## [Others](others) + +- [Average](others/) +- [Biggest of n numbers](others/) +- [Biggest Suffix](others/) +- [Fifteen Puzzle](others/) +- [Jaccard Similarity](others/) +- [Jose Phus Problem](others/) +- [Lapindrom Checker](others/) +- [Leap Year](others/) +- [Magic Square](others/) +- [Majority Element](others/) +- [Minimum subarray size with degree](others/) +- [No operator addition](others/) +- [Paint fill](others/) +- [Split list](others/) +- [Tokenizer](others/) +- [Unique number](others/) + +## License + +This work is released under MIT License. + +To the extent possible under law, [Abraham Hernandez (@abranhe)](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work.

-
- -[MIT]: https://github.com/abranhe/algorithms/blob/master/license -[MIT-logo]: https://cdn.abranhe.com/projects/algorithms/mit-license.png +
\ No newline at end of file diff --git a/scripts/formatter.js b/scripts/formatter.js deleted file mode 100644 index 6929fba..0000000 --- a/scripts/formatter.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * The All Algorithms C++ Formatter - * - * Author: Carlos Abraham Hernandez - * https://abranhe.com (abraham@abranhe.com) - */ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const glob = require('glob'); -const chalk = require('chalk'); - -const getFiles = (src, callback) => glob(src + '/**', callback); - -getFiles('../', (err, res) => { - if (err) { - console.log('Error', err); - } - - res.map((file) => { - if (path.extname(file) !== '.java') { - return; - } - }); -}); - -const categories = [ - 'artificial-intelligence', - 'backtracking', - 'bit-manipulation', - 'cellular-automaton', - 'computational-geometry', - 'cryptography', - 'data-structures', - 'divide-and-conquer', - 'dynamic-programming', - 'gaming-theory', - 'graphs', - 'greedy-algorithms', - 'math', - 'networking', - 'numerical-analysis', - 'online-challenges', - 'randomized-algorithms', - 'serches', - 'selections', - 'sorting', - 'strings', - 'no-category', -]; - -const readme = [ - ` - -
-
-
-
-
- -
-
-
-
-
-
- -
-
-

All ▲lgorithms implemented in Java

- - - - - - -
-
-allalgorithms.com -
- - - -## Contents - -You can find the All ▲lgorithms categories at [algorithms.com/categories](https://algorithms.com/categories) -`, -]; - -categories.forEach((category) => { - readme.push(` - [${category.charAt(0).toUpperCase() + category.slice(1).replace(/\-/g, ' ')}](#${category})`); -}); - -getFiles('../', (err, res) => { - let printedCategories = []; - - if (err) { - console.log('Error', err); - } - - res.map((file) => { - if (path.extname(file) !== '.java') { - return; - } - - let algorithmName = path.basename(file).replace('.java', '').replace(/([a-z0-9])([A-Z])/g, '$1 $2'); - let currentCategory = path.parse(file).dir.split(path.sep)[1]; - - if (!printedCategories.includes(currentCategory)) { - printedCategories.push(currentCategory); - readme.push( - `\n## ${currentCategory.charAt(0).toUpperCase() + currentCategory.slice(1).replace(/\-/g, ' ')}\n`, - ); - } - - readme.push( - ` - [${algorithmName.charAt(0).toUpperCase() + algorithmName.slice(1).replace(/\_/g, ' ')}](${file.replace( - '../', - '', - )})`, - ); - }); - - readme.push(` - - -## License - -This work is released under [MIT License][MIT] - -[![MIT IMG][MIT-logo]][MIT] - -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. - -
- - - -
-
- -[MIT]: https://github.com/abranhe/algorithms/blob/master/license -[MIT-logo]: https://cdn.abranhe.com/projects/algorithms/mit-license.png -`); - - fs.writeFile(`../readme.md`, readme.join('\n'), (err) => { - if (err) throw err; - console.log(chalk.green('The file was succesfully saved!')); - }); -}); diff --git a/scripts/package.json b/scripts/package.json deleted file mode 100644 index bef28da..0000000 --- a/scripts/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "scripts", - "version": "1.0.0", - "description": "Maintaining clean the All ▲lgorithms Project", - "main": "formatter.js", - "scripts": { - "validate": "node validate.js", - "format": "node formatter.js" - }, - "license": "MIT", - "private": true, - "dependencies": { - "camelcase": "^5.3.1", - "chalk": "^2.4.2", - "glob": "^7.1.3" - } -} diff --git a/scripts/validate.js b/scripts/validate.js deleted file mode 100644 index cf71f8e..0000000 --- a/scripts/validate.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * validate.js - * - * The All ▲lgorithms validator CLI - * - * Author: Carlos Abraham Hernandez - * https://abranhe.com (abraham@abranhe.com) - */ -'use strict'; - -const glob = require('glob'); -const path = require('path'); -const camelCase = require('camelcase'); -const chalk = require('chalk'); - -const getFiles = (src, callback) => glob(src + '/**', callback); - -getFiles('../', (err, res) => { - if (err) { - console.log('Error', err); - } - - let invalid = false; - - res.map((file) => { - // Accept only valid Java Files - if (path.extname(file) !== '.java') { - return; - } - - if (path.basename(file, '.java') !== camelCase(path.basename(file, '.java'), { pascalCase: true })) { - console.log(`${chalk.red(path.basename(file))} does not follow the correct style.`); - invalid = true; - } else { - console.log(`${chalk.green(path.basename(file))} is ok.`); - } - }); - - if (invalid) { - throw new TypeError(`Expected the All ▲lgorithms structure.`); - } -}); diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 0000000..e69de29 From 04119852a809326f1089e05505dd975ff0946dc2 Mon Sep 17 00:00:00 2001 From: nishantmovaliya <63806205+nishantmovaliya@users.noreply.github.com> Date: Fri, 2 Oct 2020 19:17:28 +0530 Subject: [PATCH 05/46] Update LinearSearch.java add main method --- algorithms/searches/LinearSearch.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/algorithms/searches/LinearSearch.java b/algorithms/searches/LinearSearch.java index 204eba4..f5682cc 100644 --- a/algorithms/searches/LinearSearch.java +++ b/algorithms/searches/LinearSearch.java @@ -4,7 +4,7 @@ class LinearSearch { // This function returns index of element x in arr[] - static int search(int arr[], int n, int x) { + int search(int arr[], int n, int x) { for (int i = 0; i < n; i++) { // Return the index of the element if the element // is found @@ -16,4 +16,18 @@ static int search(int arr[], int n, int x) { return -1; } + + + public static void main(String args[]) { + LinearSearch ob = new LinearSearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.search(arr,n, x); + + if (result == -1) + System.out.println("Element not present"); + else + System.out.println("Element found at " + "index " + result); + } } From 817449d9c8ff25298222754f9a4442ca82dcb019 Mon Sep 17 00:00:00 2001 From: "ramona.burger" Date: Mon, 5 Oct 2020 16:26:01 +0200 Subject: [PATCH 06/46] add minMaxSearch --- searches/minMaxSearch.java | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 searches/minMaxSearch.java diff --git a/searches/minMaxSearch.java b/searches/minMaxSearch.java new file mode 100644 index 0000000..4892b90 --- /dev/null +++ b/searches/minMaxSearch.java @@ -0,0 +1,53 @@ +public class MinMaxSearch { + + public MinMaxSearch(){ + + } + + + public int[] searchMinMax(int[] in) { + int n = in.length; + int j = 0; + int min; + int max; + int count = 0; + if (n % 2 == 1) { + j = j - 1; + min = in[0]; + max = in[0]; + count = count + 1; + } else if (in[0] < in[1]) { + min = in[0]; + max = in[1]; + count = count + 2; + } else { + min = in[1]; + max = in[0]; + count = count + 2; + } + for (int i = 1; i <= ((n - 1) / 2); i++) { + if (in[j + 2 * i] <= in[j + 2 * i + 1]) { + if (in[j + 2 * i] < min) { + min = in[j + 2 * i]; + } + if (in[j + 2 * i + 1] > max) { + max = in[j + 2 * i + 1]; + } + count = count + 3; + } else { + if (in[j + 2 * i + 1] < min) { + min = in[j + 2 * i + 1]; + } + if (in[j + 2 * i] > max) { + max = in[j + 2 * i]; + } + count = count + 3; + } + } + + int[] MinMaxC = { min, max, count }; + return MinMaxC; + + } + +} From 0f595004744c11c68d8900b3227dbe5314c54cf0 Mon Sep 17 00:00:00 2001 From: Yash Agarwal Date: Tue, 2 Oct 2018 21:02:59 +0530 Subject: [PATCH 07/46] Added QuickSort --- sorting/QuickSort.java | 78 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 sorting/QuickSort.java diff --git a/sorting/QuickSort.java b/sorting/QuickSort.java new file mode 100644 index 0000000..6574b38 --- /dev/null +++ b/sorting/QuickSort.java @@ -0,0 +1,78 @@ +// Java program for implementation of QuickSort +class QuickSort +{ + /* This function takes last element as pivot, + places the pivot element at its correct + position in sorted array, and places all + smaller (smaller than pivot) to left of + pivot and all greater elements to right + of pivot */ + int partition(int arr[], int low, int high) + { + int pivot = arr[high]; + int i = (low-1); // index of smaller element + for (int j=low; j Array to be sorted, + low --> Starting index, + high --> Ending index */ + void sort(int arr[], int low, int high) + { + if (low < high) + { + /* pi is partitioning index, arr[pi] is + now at right place */ + int pi = partition(arr, low, high); + + // Recursively sort elements before + // partition and after partition + sort(arr, low, pi-1); + sort(arr, pi+1, high); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i Date: Tue, 2 Oct 2018 21:06:51 +0530 Subject: [PATCH 08/46] Added ShellSort --- sorting/ShellSort.java | 58 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 sorting/ShellSort.java diff --git a/sorting/ShellSort.java b/sorting/ShellSort.java new file mode 100644 index 0000000..2be3987 --- /dev/null +++ b/sorting/ShellSort.java @@ -0,0 +1,58 @@ +class ShellSort +{ + /* An utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i 0; gap /= 2) + { + // Do a gapped insertion sort for this gap size. + // The first gap elements a[0..gap-1] are already + // in gapped order keep adding one more element + // until the entire array is gap sorted + for (int i = gap; i < n; i += 1) + { + // add a[i] to the elements that have been gap + // sorted save a[i] in temp and make a hole at + // position i + int temp = arr[i]; + + // shift earlier gap-sorted elements up until + // the correct location for a[i] is found + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; + + // put temp (the original a[i]) in its correct + // location + arr[j] = temp; + } + } + return 0; + } + + // Driver method + public static void main(String args[]) + { + int arr[] = {12, 34, 54, 2, 3}; + System.out.println("Array before sorting"); + printArray(arr); + + ShellSort ob = new ShellSort(); + ob.sort(arr); + + System.out.println("Array after sorting"); + printArray(arr); + } +} \ No newline at end of file From e8972c1b32b72a22143709ce969eac0e289f26b1 Mon Sep 17 00:00:00 2001 From: k3v1n Date: Tue, 2 Oct 2018 21:35:09 +0200 Subject: [PATCH 09/46] Add algorithm to determine the number of divisor digits in a given number --- math/NumberOfDivisorDigits.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 math/NumberOfDivisorDigits.java diff --git a/math/NumberOfDivisorDigits.java b/math/NumberOfDivisorDigits.java new file mode 100644 index 0000000..e69fc1a --- /dev/null +++ b/math/NumberOfDivisorDigits.java @@ -0,0 +1,18 @@ +public class NumberOfDivisorDigits { + + public static int getNumberOfDivisorDigits(final int number) { + int mutatedNumber = number; + int numberOfEvenlyDivides = 0; + + while(mutatedNumber > 0) { + final int digit = mutatedNumber % 10; + mutatedNumber = mutatedNumber / 10; + + if (digit != 0 && number % digit == 0) { + numberOfEvenlyDivides += 1; + } + } + + return numberOfEvenlyDivides; + } +} \ No newline at end of file From e875872a25c2bb4db47f054abfd76bdfd0377a16 Mon Sep 17 00:00:00 2001 From: tadipatrisudheerreddy Date: Mon, 1 Oct 2018 21:45:14 -0700 Subject: [PATCH 10/46] Add Binary Tree traversals and regular problems --- .../algos/practice/BinaryTree.java | 52 ++++++++++++++++ .../algos/practice/LowestCommonAncestor.java | 45 ++++++++++++++ .../BinaryTrees/algos/practice/SubTree.java | 60 +++++++++++++++++++ .../BinaryTrees/algos/practice/TreeNode.java | 35 +++++++++++ .../algos/practice/TreeTraversal.java | 28 +++++++++ .../algos/practice/TreeWithNoSiblings.java | 33 ++++++++++ 6 files changed, 253 insertions(+) create mode 100644 BinaryTrees-traversals/BinaryTrees/algos/practice/BinaryTree.java create mode 100644 BinaryTrees-traversals/BinaryTrees/algos/practice/LowestCommonAncestor.java create mode 100644 BinaryTrees-traversals/BinaryTrees/algos/practice/SubTree.java create mode 100644 BinaryTrees-traversals/BinaryTrees/algos/practice/TreeNode.java create mode 100644 BinaryTrees-traversals/BinaryTrees/algos/practice/TreeTraversal.java create mode 100644 BinaryTrees-traversals/BinaryTrees/algos/practice/TreeWithNoSiblings.java diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/BinaryTree.java b/BinaryTrees-traversals/BinaryTrees/algos/practice/BinaryTree.java new file mode 100644 index 0000000..2b87783 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTrees/algos/practice/BinaryTree.java @@ -0,0 +1,52 @@ +package algos.practice; + +public class BinaryTree { + + public static TreeNode mirrorTree(TreeNode node){ + if(node == null) + return node; + + TreeNode left = mirrorTree(node.left); + TreeNode right = mirrorTree(node.right); + node.left = right; + node.right = left; + + return node; + } + + public static void main(String[] args){ + + TreeNode root = new TreeNode(8); + TreeNode.insert(root, new TreeNode(31)); + TreeNode.insert(root, new TreeNode(45)); + TreeNode.insert(root, new TreeNode(16)); + TreeNode.insert(root, new TreeNode(24)); + TreeNode.insert(root, new TreeNode(19)); + TreeNode.insert(root, new TreeNode(29)); + TreeNode.insert(root, new TreeNode(7)); + + StringBuffer inorderbuf=new StringBuffer(); + StringBuffer preorderbuf=new StringBuffer(); + StringBuffer postorderbuf=new StringBuffer(); + + + TreeTraversal.getInorder(root,inorderbuf); + TreeTraversal.getPreorder(root, preorderbuf); + TreeTraversal.getPostorder(root, postorderbuf); + + System.out.println("Before mirroring,In order tree is: "+inorderbuf); + + BinaryTree.mirrorTree(root); + + StringBuffer inorderbufAfter = new StringBuffer(); + TreeTraversal.getInorder(root, inorderbufAfter); + System.out.println("After mirroring,In order tree is: "+inorderbufAfter); + + System.out.println("Post order traversal:" + postorderbuf); + System.out.println("Pre order traversal:"+ preorderbuf); + + System.out.println("Nodes with no siblings:"); + TreeWithNoSiblings.printOnlyLeaves(root); + + } +} diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/LowestCommonAncestor.java b/BinaryTrees-traversals/BinaryTrees/algos/practice/LowestCommonAncestor.java new file mode 100644 index 0000000..0407106 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTrees/algos/practice/LowestCommonAncestor.java @@ -0,0 +1,45 @@ +package algos.practice; + +public class LowestCommonAncestor { + + TreeNode root; + + public TreeNode LCA(int p,int q){ + return findLCA(root,p,q); + } + + private TreeNode findLCA(TreeNode root, int p, int q) { + if(root == null) + return null; + if(root.value == p || root.value == q) + return root; + + TreeNode left = findLCA(root.left,p,q); + TreeNode right = findLCA(root.right,p,q); + + if(left!=null && right!=null) + return root; + + return left!=null? left : right; + } + + + + public static void main(String[] args){ + + LowestCommonAncestor lca = new LowestCommonAncestor(); + + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.left = new TreeNode(4); + root.left.right = new TreeNode(5); + root.right.left = new TreeNode(6); + root.right.right = new TreeNode(7); + + + System.out.println("Lowest Common Ancestor of (4,5): "+ lca.findLCA(root, 4, 5).value); + System.out.println("Lowest Common Ancestor of (4,6): "+ lca.findLCA(root, 4, 6).value); + System.out.println("Lowest Common Ancestor of (3,4): "+ lca.findLCA(root, 3, 4).value); + } +} diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/SubTree.java b/BinaryTrees-traversals/BinaryTrees/algos/practice/SubTree.java new file mode 100644 index 0000000..20de5b0 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTrees/algos/practice/SubTree.java @@ -0,0 +1,60 @@ +package algos.practice; + +public class SubTree { + + TreeNode root1, root2; + + public boolean isIdentical(TreeNode root1,TreeNode root2){ + + //Since every null tree is also subset of main tree + if(root1==null&&root2==null) + return true; + //Need to check the null condition only once,since we are using recursion at second time it should not be null + if(root1==null&&root2==null) + return false; + + return (root1.value==root2.value)&& (isIdentical(root1.left,root2.left)) + &&((isIdentical(root1.right,root2.right)) ); + } + + public boolean isSubTree(TreeNode p, TreeNode q){ + + //Since every null tree is also subset of main tree + if(q==null) + return true; + + if(p==null) + return false; + + if(isIdentical(p,q)) + return true; + + return isSubTree(p.left,q)||isSubTree(p.right,q); + } + + + public static void main(String[] args) { + + SubTree tree = new SubTree(); + + TreeNode root1 = new TreeNode(26); + root1.right = new TreeNode(3); + root1.right.right = new TreeNode(3); + root1.left = new TreeNode(10); + root1.left.left = new TreeNode(4); + root1.left.left.right = new TreeNode(30); + root1.left.right = new TreeNode(6); + + TreeNode root2 = new TreeNode(10); + root2.right = new TreeNode(6); + root2.left = new TreeNode(4); + root2.left.right = new TreeNode(30); + + if(tree.isSubTree(tree.root1,tree.root2)) + System.out.println("Tree2 is subtree of Tree1"); + else + System.out.println("Tree2 is not a subtree of Tree1"); + + } + +} diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeNode.java b/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeNode.java new file mode 100644 index 0000000..c6ab982 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeNode.java @@ -0,0 +1,35 @@ +package algos.practice; + +public class TreeNode { + + int value; + TreeNode left; + TreeNode right; + + public TreeNode(int i) { + value = i; + left = right = null; + } + + public static boolean insert(TreeNode root,TreeNode n){ + if(n!=null){ + if(n.value >= root.value){ + if(root.right==null){ + root.right=n; + return true; + } + else + return insert(root.right,n); + } + else if(root.left==null){ + root.left=n; + return true; + } + else + return insert(root.left,n); + } + return false; + + } + +} diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeTraversal.java b/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeTraversal.java new file mode 100644 index 0000000..5283a56 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeTraversal.java @@ -0,0 +1,28 @@ +package algos.practice; + +public class TreeTraversal { + + public static void getInorder(TreeNode node,StringBuffer buf){ + if(node == null) + return; + getInorder(node.left,buf); + buf.append(" "+node.value); + getInorder(node.right,buf); + } + + public static void getPreorder(TreeNode node,StringBuffer buf){ + if(node==null) + return; + buf.append(" "+node.value); + getPreorder(node.left,buf); + getPreorder(node.right,buf); + } + + public static void getPostorder(TreeNode node,StringBuffer buf){ + if(node==null) + return; + getPostorder(node.left,buf); + getPostorder(node.right,buf); + buf.append(" "+node.value); + } +} diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeWithNoSiblings.java b/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeWithNoSiblings.java new file mode 100644 index 0000000..13211f4 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeWithNoSiblings.java @@ -0,0 +1,33 @@ +package algos.practice; + +public class TreeWithNoSiblings { + public static void printOnlyLeaves(TreeNode node){ + if(node!=null){ + + printOnlyLeaves(node.left); + + if ((node.left==null) && (node.right!=null)) + System.out.println("Node with no sibling in right side is: " + node.right.value); + + if((node.left!=null) && (node.right==null)) + System.out.println("Node with no sibling in left side is: " + node.left.value); + + printOnlyLeaves(node.right); + } + } + + public static void main(String[] args){ + + TreeNode root = new TreeNode(50); + TreeNode.insert(root, new TreeNode(30)); + TreeNode.insert(root, new TreeNode(60)); + TreeNode.insert(root, new TreeNode(22)); + TreeNode.insert(root, new TreeNode(38)); + TreeNode.insert(root, new TreeNode(55)); + TreeNode.insert(root, new TreeNode(34)); + + + TreeWithNoSiblings.printOnlyLeaves(root); + } + +} From 5aa64f2278c094d5362d1022b903518b09bb014c Mon Sep 17 00:00:00 2001 From: tadipatrisudheerreddy Date: Tue, 2 Oct 2018 18:30:39 -0700 Subject: [PATCH 11/46] Make the folder structure and code format in the files --- .../{BinaryTrees/algos/practice => }/BinaryTree.java | 8 +++++++- .../algos/practice => }/LowestCommonAncestor.java | 7 ++++++- .../{BinaryTrees/algos/practice => }/SubTree.java | 8 ++++++-- .../{BinaryTrees/algos/practice => }/TreeNode.java | 7 ++++++- .../{BinaryTrees/algos/practice => }/TreeTraversal.java | 7 ++++++- .../algos/practice => }/TreeWithNoSiblings.java | 7 ++++++- 6 files changed, 37 insertions(+), 7 deletions(-) rename BinaryTrees-traversals/{BinaryTrees/algos/practice => }/BinaryTree.java (91%) rename BinaryTrees-traversals/{BinaryTrees/algos/practice => }/LowestCommonAncestor.java (88%) rename BinaryTrees-traversals/{BinaryTrees/algos/practice => }/SubTree.java (91%) rename BinaryTrees-traversals/{BinaryTrees/algos/practice => }/TreeNode.java (80%) rename BinaryTrees-traversals/{BinaryTrees/algos/practice => }/TreeTraversal.java (82%) rename BinaryTrees-traversals/{BinaryTrees/algos/practice => }/TreeWithNoSiblings.java (85%) diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/BinaryTree.java b/BinaryTrees-traversals/BinaryTree.java similarity index 91% rename from BinaryTrees-traversals/BinaryTrees/algos/practice/BinaryTree.java rename to BinaryTrees-traversals/BinaryTree.java index 2b87783..d69b9f1 100644 --- a/BinaryTrees-traversals/BinaryTrees/algos/practice/BinaryTree.java +++ b/BinaryTrees-traversals/BinaryTree.java @@ -1,4 +1,10 @@ -package algos.practice; +/** + * Binary Tree Traversals implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + public class BinaryTree { diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/LowestCommonAncestor.java b/BinaryTrees-traversals/LowestCommonAncestor.java similarity index 88% rename from BinaryTrees-traversals/BinaryTrees/algos/practice/LowestCommonAncestor.java rename to BinaryTrees-traversals/LowestCommonAncestor.java index 0407106..eb74e5b 100644 --- a/BinaryTrees-traversals/BinaryTrees/algos/practice/LowestCommonAncestor.java +++ b/BinaryTrees-traversals/LowestCommonAncestor.java @@ -1,4 +1,9 @@ -package algos.practice; +/** + * To find Lowest Common Ancestor for a binary tree implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ public class LowestCommonAncestor { diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/SubTree.java b/BinaryTrees-traversals/SubTree.java similarity index 91% rename from BinaryTrees-traversals/BinaryTrees/algos/practice/SubTree.java rename to BinaryTrees-traversals/SubTree.java index 20de5b0..ed8d10d 100644 --- a/BinaryTrees-traversals/BinaryTrees/algos/practice/SubTree.java +++ b/BinaryTrees-traversals/SubTree.java @@ -1,5 +1,9 @@ -package algos.practice; - +/** + * Binary Tree Identical implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ public class SubTree { TreeNode root1, root2; diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeNode.java b/BinaryTrees-traversals/TreeNode.java similarity index 80% rename from BinaryTrees-traversals/BinaryTrees/algos/practice/TreeNode.java rename to BinaryTrees-traversals/TreeNode.java index c6ab982..11ad3a0 100644 --- a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeNode.java +++ b/BinaryTrees-traversals/TreeNode.java @@ -1,4 +1,9 @@ -package algos.practice; +/** + * Binary Tree Node implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ public class TreeNode { diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeTraversal.java b/BinaryTrees-traversals/TreeTraversal.java similarity index 82% rename from BinaryTrees-traversals/BinaryTrees/algos/practice/TreeTraversal.java rename to BinaryTrees-traversals/TreeTraversal.java index 5283a56..9443295 100644 --- a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeTraversal.java +++ b/BinaryTrees-traversals/TreeTraversal.java @@ -1,4 +1,9 @@ -package algos.practice; +/** + * Binary Tree Traversals implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ public class TreeTraversal { diff --git a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeWithNoSiblings.java b/BinaryTrees-traversals/TreeWithNoSiblings.java similarity index 85% rename from BinaryTrees-traversals/BinaryTrees/algos/practice/TreeWithNoSiblings.java rename to BinaryTrees-traversals/TreeWithNoSiblings.java index 13211f4..d0dffb1 100644 --- a/BinaryTrees-traversals/BinaryTrees/algos/practice/TreeWithNoSiblings.java +++ b/BinaryTrees-traversals/TreeWithNoSiblings.java @@ -1,4 +1,9 @@ -package algos.practice; +/** + * To find the Tree with no siblings - implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ public class TreeWithNoSiblings { public static void printOnlyLeaves(TreeNode node){ From f128ad8cd9e983e09aea132e2fdbae628ce4978c Mon Sep 17 00:00:00 2001 From: Bhawesh Bhansali Date: Tue, 2 Oct 2018 09:53:42 +0530 Subject: [PATCH 12/46] Bellman Ford algorithm --- BellmanFord algo | 95 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 BellmanFord algo diff --git a/BellmanFord algo b/BellmanFord algo new file mode 100644 index 0000000..9a16e01 --- /dev/null +++ b/BellmanFord algo @@ -0,0 +1,95 @@ +import java.util.Scanner; + +public class BellmanFord +{ + private int distances[]; + private int numberofvertices; + public static final int MAX_VALUE = 999; + + public BellmanFord(int numberofvertices) + { + this.numberofvertices = numberofvertices; + distances = new int[numberofvertices + 1]; + } + + public void BellmanFordEvaluation(int source, int adjacencymatrix[][]) + { + for (int node = 1; node <= numberofvertices; node++) + { + distances[node] = MAX_VALUE; + } + + distances[source] = 0; + for (int node = 1; node <= numberofvertices - 1; node++) + { + for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) + { + for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) + { + if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE) + { + if (distances[destinationnode] > distances[sourcenode] + + adjacencymatrix[sourcenode][destinationnode]) + distances[destinationnode] = distances[sourcenode] + + adjacencymatrix[sourcenode][destinationnode]; + } + } + } + } + + for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) + { + for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) + { + if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE) + { + if (distances[destinationnode] > distances[sourcenode] + + adjacencymatrix[sourcenode][destinationnode]) + System.out.println("The Graph contains negative egde cycle"); + } + } + } + + for (int vertex = 1; vertex <= numberofvertices; vertex++) + { + System.out.println("distance of source " + source + " to " + + vertex + " is " + distances[vertex]); + } + } + + public static void main(String... arg) + { + int numberofvertices = 0; + int source; + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter the number of vertices"); + numberofvertices = scanner.nextInt(); + + int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1]; + System.out.println("Enter the adjacency matrix"); + for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) + { + for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) + { + adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt(); + if (sourcenode == destinationnode) + { + adjacencymatrix[sourcenode][destinationnode] = 0; + continue; + } + if (adjacencymatrix[sourcenode][destinationnode] == 0) + { + adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE; + } + } + } + + System.out.println("Enter the source vertex"); + source = scanner.nextInt(); + + BellmanFord bellmanford = new BellmanFord(numberofvertices); + bellmanford.BellmanFordEvaluation(source, adjacencymatrix); + scanner.close(); + } +} From 19f25ac0de753d5495f3edae57c801cfffd5c1e2 Mon Sep 17 00:00:00 2001 From: bhawesh96 Date: Wed, 3 Oct 2018 09:29:55 +0530 Subject: [PATCH 13/46] moved to folder and added extension --- BellmanFord algo => graph-algorithms/BellmanFord.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename BellmanFord algo => graph-algorithms/BellmanFord.java (100%) diff --git a/BellmanFord algo b/graph-algorithms/BellmanFord.java similarity index 100% rename from BellmanFord algo rename to graph-algorithms/BellmanFord.java From 3a6d19553148e0ff872d07e7b0f083349a824539 Mon Sep 17 00:00:00 2001 From: Bhawesh Bhansali Date: Tue, 2 Oct 2018 10:03:05 +0530 Subject: [PATCH 14/46] Dijkstra's algorithm --- Dijkstra | 141 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 Dijkstra diff --git a/Dijkstra b/Dijkstra new file mode 100644 index 0000000..682fb39 --- /dev/null +++ b/Dijkstra @@ -0,0 +1,141 @@ +import java.util.HashSet; +import java.util.InputMismatchException; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; +import java.util.Set; + +public class DijkstraQueue +{ + private int distances[]; + private Queue queue; + private Set settled; + private int number_of_nodes; + private int adjacencyMatrix[][]; + + public DijkstraQueue(int number_of_nodes) + { + this.number_of_nodes = number_of_nodes; + distances = new int[number_of_nodes + 1]; + settled = new HashSet(); + queue = new LinkedList(); + adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1]; + } + + public void dijkstra_algorithm(int adjacency_matrix[][], int source) + { + int evaluationNode; + for (int i = 1; i <= number_of_nodes; i++) + for (int j = 1; j <= number_of_nodes; j++) + adjacencyMatrix[i][j] = adjacency_matrix[i][j]; + + for (int i = 1; i <= number_of_nodes; i++) + { + distances[i] = Integer.MAX_VALUE; + } + + queue.add(source); + distances[source] = 0; + + while (!queue.isEmpty()) + { + evaluationNode = getNodeWithMinimumDistanceFromQueue(); + settled.add(evaluationNode); + evaluateNeighbours(evaluationNode); + } + } + + private int getNodeWithMinimumDistanceFromQueue() + { + int min ; + int node = 0; + Iterator iterator = queue.iterator(); + node = iterator.next(); + min = distances[node]; + + for (int i = 1; i <= distances.length; i++) + { + if (queue.contains(i)) + { + if (distances[i] <= min) + { + min = distances[i]; + node = i; + } + } + } + queue.remove(node); + return node; + } + + private void evaluateNeighbours(int evaluationNode) + { + int edgeDistance = -1; + int newDistance = -1; + + for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++) + { + if (!settled.contains(destinationNode)) + { + if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE) + { + edgeDistance = adjacencyMatrix[evaluationNode][destinationNode]; + newDistance = distances[evaluationNode] + edgeDistance; + if (newDistance < distances[destinationNode]) + { + distances[destinationNode] = newDistance; + } + queue.add(destinationNode); + } + } + } + } + + public static void main(String... arg) + { + int adjacency_matrix[][]; + int number_of_vertices; + int source = 0; + Scanner scan = new Scanner(System.in); + + try + { + System.out.println("Enter the number of vertices"); + number_of_vertices = scan.nextInt(); + adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1]; + + System.out.println("Enter the Weighted Matrix for the graph"); + for (int i = 1; i <= number_of_vertices; i++) + { + for (int j = 1; j <= number_of_vertices; j++) + { + adjacency_matrix[i][j] = scan.nextInt(); + if (i == j) + { + adjacency_matrix[i][j] = 0; + continue; + } + if (adjacency_matrix[i][j] == 0) + { + adjacency_matrix[i][j] = Integer.MAX_VALUE; + } + } + } + + System.out.println("Enter the source "); + source = scan.nextInt(); + DijkstraQueue dijkstrasQueue = new DijkstraQueue(number_of_vertices); + dijkstrasQueue.dijkstra_algorithm(adjacency_matrix, source); + + System.out.println("The Shorted Path to all nodes are "); + for (int i = 1; i <= dijkstrasQueue.distances.length - 1; i++) + { + System.out.println(source + " to " + i + " is " + dijkstrasQueue.distances[i]); + } + } catch (InputMismatchException inputMismatch) + { + System.out.println("Wrong Input Format"); + } + scan.close(); + } +} From 4e779ea65ef58369cd34007a84954a413ecdd04d Mon Sep 17 00:00:00 2001 From: bhawesh96 Date: Wed, 3 Oct 2018 09:35:54 +0530 Subject: [PATCH 15/46] moved to folder and added .java extension --- Dijkstra => graph-algorithms/Dijkstra.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dijkstra => graph-algorithms/Dijkstra.java (100%) diff --git a/Dijkstra b/graph-algorithms/Dijkstra.java similarity index 100% rename from Dijkstra rename to graph-algorithms/Dijkstra.java From 5ea45174ff43d2ae0515e23d1edd91ce22f905aa Mon Sep 17 00:00:00 2001 From: Bhawesh Bhansali Date: Tue, 2 Oct 2018 09:57:22 +0530 Subject: [PATCH 16/46] DFS --- DFS | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 DFS diff --git a/DFS b/DFS new file mode 100644 index 0000000..ceefd1f --- /dev/null +++ b/DFS @@ -0,0 +1,74 @@ +import java.util.InputMismatchException; +import java.util.Scanner; +import java.util.Stack; + +public class DFS +{ + private Stack stack; + + public DFS() + { + stack = new Stack(); + } + + public void dfs(int adjacency_matrix[][], int source) + { + int number_of_nodes = adjacency_matrix[source].length - 1; + + int visited[] = new int[number_of_nodes + 1]; + int element = source; + int i = source; + System.out.print(element + "\t"); + visited[source] = 1; + stack.push(source); + + while (!stack.isEmpty()) + { + element = stack.peek(); + i = element; + while (i <= number_of_nodes) + { + if (adjacency_matrix[element][i] == 1 && visited[i] == 0) + { + stack.push(i); + visited[i] = 1; + element = i; + i = 1; + System.out.print(element + "\t"); + continue; + } + i++; + } + stack.pop(); + } + } + + public static void main(String...arg) + { + int number_of_nodes, source; + Scanner scanner = null; + try + { + System.out.println("Enter the number of nodes in the graph"); + scanner = new Scanner(System.in); + number_of_nodes = scanner.nextInt(); + + int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1]; + System.out.println("Enter the adjacency matrix"); + for (int i = 1; i <= number_of_nodes; i++) + for (int j = 1; j <= number_of_nodes; j++) + adjacency_matrix[i][j] = scanner.nextInt(); + + System.out.println("Enter the source for the graph"); + source = scanner.nextInt(); + + System.out.println("The DFS Traversal for the graph is given by "); + DFS dfs = new DFS(); + dfs.dfs(adjacency_matrix, source); + }catch(InputMismatchException inputMismatch) + { + System.out.println("Wrong Input format"); + } + scanner.close(); + } +} From 99b9b1677275c08b6d4ba21d7434056f8db1ac28 Mon Sep 17 00:00:00 2001 From: bhawesh96 Date: Wed, 3 Oct 2018 09:33:03 +0530 Subject: [PATCH 17/46] moved to folder and added .java extension --- DFS => graph-algorithms/DFS.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DFS => graph-algorithms/DFS.java (100%) diff --git a/DFS b/graph-algorithms/DFS.java similarity index 100% rename from DFS rename to graph-algorithms/DFS.java From 6e7e8b9d512e0b96ea964c9f57425a61b1727548 Mon Sep 17 00:00:00 2001 From: Sanghamitra1234 Date: Thu, 4 Oct 2018 01:22:13 +0530 Subject: [PATCH 18/46] Hashing problem added --- Hashing/Isograms.java | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Hashing/Isograms.java diff --git a/Hashing/Isograms.java b/Hashing/Isograms.java new file mode 100644 index 0000000..373b7ac --- /dev/null +++ b/Hashing/Isograms.java @@ -0,0 +1,40 @@ +import java.lang.*; +import java.io.*; +class Isogram + { + public static boolean Check(String s){ + HashSeth=new HashSet<>(); + for(int i=0;i Date: Tue, 2 Oct 2018 12:05:15 +0530 Subject: [PATCH 19/46] Adding Huffman Coding Algorithm --- greedyalgorithms/HuffmanCoding.java | 125 ++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 greedyalgorithms/HuffmanCoding.java diff --git a/greedyalgorithms/HuffmanCoding.java b/greedyalgorithms/HuffmanCoding.java new file mode 100644 index 0000000..e2fa247 --- /dev/null +++ b/greedyalgorithms/HuffmanCoding.java @@ -0,0 +1,125 @@ +import java.util.PriorityQueue; +import java.util.Scanner; +import java.util.Comparator; + +// Implementation of Hoffman Coding algoritms. +class HuffmanNode { + + int data; + char c; + HuffmanNode left; + HuffmanNode right; +} + +// comparator class helps to compare the node +// on the basis of one of its attribute. +// Here we will be compared +// on the basis of data values of the nodes. +class MyComparator implements Comparator { + public int compare(HuffmanNode x, HuffmanNode y) + { + + return x.data - y.data; + } +} + +public class Huffman { + + // recursive function to print the + // huffman-code through the tree traversal. + // Here s is the huffman - code generated. + public static void printCode(HuffmanNode root, String s) + { + + // base case; if the left and right are null + // then its a leaf node and we print + // the code s generated by traversing the tree. + if (root.left == null && root.right == null && Character.isLetter(root.c)) { + // c is the character in the node + System.out.println(root.c + ":" + s); + return; + } + + // if we go to left then add "0" to the code. + // if we go to the right add"1" to the code. + + // recursive calls for left and + // right sub-tree of the generated tree. + printCode(root.left, s + "0"); + printCode(root.right, s + "1"); + } + + // main function + public static void main(String[] args) + { + + Scanner s = new Scanner(System.in); + // number of characters. + int n = 6; + char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; + int[] charfreq = { 5, 9, 12, 13, 16, 45 }; + + // creating a priority queue q. + // makes a min-priority queue(min-heap). + PriorityQueue q + = new PriorityQueue(n, new MyComparator()); + + for (int i = 0; i < n; i++) { + + // creating a huffman node object + // and adding it to the priority-queue. + HuffmanNode hn = new HuffmanNode(); + + hn.c = charArray[i]; + hn.data = charfreq[i]; + + hn.left = null; + hn.right = null; + + // add functions adds + // the huffman node to the queue. + q.add(hn); + } + + // create a root node + HuffmanNode root = null; + + // Here we will extract the two minimum value + // from the heap each time until + // its size reduces to 1, extract until + // all the nodes are extracted. + while (q.size() > 1) { + + // first min extract. + HuffmanNode x = q.peek(); + q.poll(); + + // second min extarct. + HuffmanNode y = q.peek(); + q.poll(); + + // new node f which is equal + HuffmanNode f = new HuffmanNode(); + + // to the sum of the frequency of the two nodes + // assigning values to the f node. + f.data = x.data + y.data; + f.c = '-'; + + // first extracted node as left child. + f.left = x; + + // second extracted node as the right child. + f.right = y; + + // marking the f node as the root node. + root = f; + + // add this node to the priority-queue. + q.add(f); + } + + // print the codes by traversing the tree + printCode(root, ""); + } +} From 81b64c8fe30af13c67a4eeb65c38bec92871811d Mon Sep 17 00:00:00 2001 From: aayushi2601 Date: Thu, 4 Oct 2018 09:44:20 +0530 Subject: [PATCH 20/46] Renaming folder --- {greedyalgorithms => greedy-algorithms}/HuffmanCoding.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {greedyalgorithms => greedy-algorithms}/HuffmanCoding.java (100%) diff --git a/greedyalgorithms/HuffmanCoding.java b/greedy-algorithms/HuffmanCoding.java similarity index 100% rename from greedyalgorithms/HuffmanCoding.java rename to greedy-algorithms/HuffmanCoding.java From 7df087048b8f4736da193a29563f6abb05731549 Mon Sep 17 00:00:00 2001 From: miqdadyyy Date: Thu, 4 Oct 2018 10:50:11 +0700 Subject: [PATCH 21/46] Add BFS Algorithm --- graph/BFS.java | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 graph/BFS.java diff --git a/graph/BFS.java b/graph/BFS.java new file mode 100644 index 0000000..e6215c9 --- /dev/null +++ b/graph/BFS.java @@ -0,0 +1,97 @@ + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +/** + * + * @author miqdad + */ + +class Node{ + int value; + int index; // represent index of node + boolean isVisited; + ArrayList neighbor; + + public Node(int index, int value){ + this.index = index; + this.value = value; + this.neighbor = new ArrayList(); + this.isVisited = false; + } + + public void addNeighbor(Node node){ + this.neighbor.add(node); + } +} + +class Graph{ + int totalNode; + Node[] nodes; + + public Graph(int totalNode){ + this.totalNode = totalNode; + nodes = new Node[totalNode]; + for(int i=0; i initQueue = new LinkedList(); + initQueue.add(root); + BFS(initQueue); + } + + public void BFS(Queue queue){ + if(queue.isEmpty()){ // check if there is no neighbor + return; + } + Queue nextQueue = new LinkedList(); + while(!queue.isEmpty()){ + Node node = queue.poll(); // take neighbor + if(!nodes[node.index].isVisited){ // check neighbor node is visited or not by his index + nodes[node.index].isVisited = true; // set visited to true on graph global variable + System.out.print(node.value + " "); // print the node + for(Node n : node.neighbor){ + if(!nodes[n.index].isVisited){ + nextQueue.add(n); // insert every neighbor to nextqueue + } + } + } + } + + BFS(nextQueue); // recursive visiting node + } +} + +public class BFS { + public static void main(String[] args){ + Graph graph = new Graph(10); // 10 nodes in this graph + for(Node n : graph.nodes){ + System.out.printf("Node index %d has value %d\n", n.index, n.value); + } + + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(0, 3); + graph.addEdge(1, 4); + graph.addEdge(1, 5); + graph.addEdge(2, 6); + graph.addEdge(2, 7); + graph.addEdge(3, 8); + graph.addEdge(3, 9); + graph.addEdge(1, 7); + + graph.initBFS(); + } +} From 53e8546cafba783b55b5ea16bb62639975fe880b Mon Sep 17 00:00:00 2001 From: miqdadyyy Date: Thu, 4 Oct 2018 11:13:46 +0700 Subject: [PATCH 22/46] Add DFS DFS Search Pattern --- DFS.java | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 DFS.java diff --git a/DFS.java b/DFS.java new file mode 100644 index 0000000..4faa384 --- /dev/null +++ b/DFS.java @@ -0,0 +1,89 @@ + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +/** + * + * @author miqdad + */ +class Node { + + int value; + int index; // represent index of node + boolean isVisited; + ArrayList neighbor; + + public Node(int index, int value) { + this.index = index; + this.value = value; + this.neighbor = new ArrayList(); + this.isVisited = false; + } + + public void addNeighbor(Node node) { + this.neighbor.add(node); + } +} + +class Graph { + + int totalNode; + Node[] nodes; + + public Graph(int totalNode) { + this.totalNode = totalNode; + nodes = new Node[totalNode]; + for (int i = 0; i < totalNode; i++) { + int value = (int) (Math.random() * 100); // gives random value to node + nodes[i] = new Node(i, value); + } + } + + public void addEdge(int s, int d) { // index node +// add neighbor each other + nodes[s].addNeighbor(nodes[d]); + nodes[d].addNeighbor(nodes[s]); + } + + public void initDFS() { + Node root = nodes[0]; + DFS(root); + } + + public void DFS(Node node) { + if (!nodes[node.index].isVisited) { + System.out.print(node.value + " "); + node.isVisited = true; + } + for (Node n : node.neighbor) { + if(!n.isVisited){ + DFS(n); + } + } + + } +} + +public class DFS { + public static void main(String[] args){ + Graph graph = new Graph(10); // 10 nodes in this graph + for(Node n : graph.nodes){ + System.out.printf("Node index %d has value %d\n", n.index, n.value); + } + + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(0, 3); + graph.addEdge(1, 4); + graph.addEdge(1, 5); + graph.addEdge(2, 6); + graph.addEdge(2, 7); + graph.addEdge(3, 8); + graph.addEdge(3, 9); + graph.addEdge(1, 7); + + graph.initDFS(); + System.out.println(""); + } +} From bd3dc45201a1b17c9486b3b3643eedf29214b91d Mon Sep 17 00:00:00 2001 From: Miqdad Yanuar Farcha <34906923+miqdadyyy@users.noreply.github.com> Date: Thu, 4 Oct 2018 11:16:15 +0700 Subject: [PATCH 23/46] Move directory to graph --- DFS.java => graph/DFS.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DFS.java => graph/DFS.java (100%) diff --git a/DFS.java b/graph/DFS.java similarity index 100% rename from DFS.java rename to graph/DFS.java From 8d07bbcb4cae2dd6654593b30f5eb5adbc0068c2 Mon Sep 17 00:00:00 2001 From: thiru <36688218+thirulak@users.noreply.github.com> Date: Fri, 5 Oct 2018 00:24:33 +0530 Subject: [PATCH 24/46] Added Cyclesort.java --- sorting/Cyclesort.java | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 sorting/Cyclesort.java diff --git a/sorting/Cyclesort.java b/sorting/Cyclesort.java new file mode 100644 index 0000000..aa2ab87 --- /dev/null +++ b/sorting/Cyclesort.java @@ -0,0 +1,82 @@ +// Java program to impleament cycle sort + +import java.util.*; +import java.lang.*; + +class Cyclesort +{ +// Function sort the array using Cycle sort + public static void cycleSort (int arr[], int n) + { + // count number of memory writes + int writes = 0; + + // traverse array elements and put it to on + // the right place + for (int cycle_start=0; cycle_start<=n-2; cycle_start++) + { + // initialize item as starting point + int item = arr[cycle_start]; + + // Find position where we put the item. We basically + // count all smaller elements on right side of item. + int pos = cycle_start; + for (int i = cycle_start+1; i Date: Thu, 4 Oct 2018 21:01:21 +0200 Subject: [PATCH 25/46] Add A* algorithm for pathfinding in a graph --- graph/AStarPathfinding.java | 219 ++++++++++++++++++++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 graph/AStarPathfinding.java diff --git a/graph/AStarPathfinding.java b/graph/AStarPathfinding.java new file mode 100644 index 0000000..6960123 --- /dev/null +++ b/graph/AStarPathfinding.java @@ -0,0 +1,219 @@ +import java.util.*; + +/** + * A* Pathfinding algorithm + * + * It searches for shortest path between two graph nodes using + * heuristic estimation of a distance to lower the amount of + * nodes to be visited. + * + * It works well in cases of finding a path between geographical + * objects (like cities or intersections) using connections + * between them (roads). + * + * It minimizes a function: f(x) = g(x) + h(x) where: + * g(x) is computed distance from start to x node + * h(x) is heuristic distance from x node to the target + * f(x) is the total cost of getting from start to goal through x + * + * In this example the heurestic distance is an euclidean distance + * (every node has a cartesian coordinates assigned) + * + * Wiki page about the algorithm: + * https://en.wikipedia.org/wiki/A*_search_algorithm + * + * === + * + * The algorithm is implemented in @see Graph.findShortestPathUsingAStar() + * The rest of the code helps keeping implementation clear. + * + * === + * + * @author Piotr Macha + */ + +final class Graph { + private final Map nodes = new HashMap<>(); + + List findShortestPathUsingAStar(String startName, String goalName) { + Node start = nodes.get(startName); + Node goal = nodes.get(goalName); + + // Nodes already visited + Set closedSet = new HashSet<>(); + + // Nodes already known but not visited, we put start node as first element + Set openSet = new HashSet<>(); + openSet.add(start); + + // Map to rebuild path when we found a route + Map cameFrom = new HashMap<>(); + + // g(x), g-score contains cost to get from start to given node + // We initialize it as 0 for start node and infinite for others + Map gScore = new HashMap<>(); + for (Node node : nodes.values()) { + gScore.put(node, node == start ? Distance.real(0) : Distance.infinite()); + } + + // f(x), f-score is total cost of getting from start to goal thought a specific node + // We initialize it as heuristic distance estimate for start and infinity for others + Map fScore = new HashMap<>(); + for (Node node : nodes.values()) { + fScore.put(node, node == start ? node.euqlideanDistanceTo(goal) : Distance.infinite()); + } + + while (!openSet.isEmpty()) { + // Find a node in open set with the lowest f-score + Node current = openSet.stream().min(Comparator.comparing(fScore::get)).get(); + + if (current == goal) { + // We found the path and now we can reconstruct it using cameFrom map + List path = new ArrayList<>(); + path.add(current); + while (cameFrom.keySet().contains(current)) { + current = cameFrom.get(current); + path.add(current); + } + Collections.reverse(path); + return path; + } + + // Mark node as visited by swapping its set + openSet.remove(current); + closedSet.add(current); + + for (Map.Entry neighborEntry : current.edges.entrySet()) { + Node neighbor = neighborEntry.getKey(); + Distance distance = neighborEntry.getValue(); + + if (closedSet.contains(neighbor)) { + // Ignore neighbor if it was already evaluated + continue; + } + + // Might be a new g-score for current + Distance gScoreMaybe = gScore.get(current).add(distance); + + if (!openSet.contains(neighbor)) { + // We'll evaluate the newly discovered node later + openSet.add(neighbor); + } else if (gScoreMaybe.compareTo(gScore.get(neighbor)) >= 0) { + // Path is worse than already discovered + continue; + } + + // We'll use it later to reconstruct the path + cameFrom.put(neighbor, current); + + // We set f(x) as g(x) + h(x) (heuristic distance) + gScore.put(neighbor, gScoreMaybe); + fScore.put(neighbor, gScoreMaybe.add(neighbor.euqlideanDistanceTo(goal))); + } + } + + throw new RuntimeException("A* reached end without finding a route (unexpected case)"); + } + + Graph add(Node node) { + this.nodes.put(node.name, node); + return this; + } + + Graph edge(String from, String to, double distance) { + Node a = nodes.get(from); + Node b = nodes.get(to); + a.edges.put(b, Distance.real(distance)); + b.edges.put(a, Distance.real(distance)); + return this; + } + + final static class Distance implements Comparable { + private final boolean infinite; + private final double distance; + + private Distance(boolean infinite, double distance) { + this.infinite = infinite; + this.distance = distance; + } + + Distance add(Distance o) { + return new Distance(this.infinite && o.infinite, this.distance + o.distance); + } + + static Distance infinite() { + return new Distance(true, 0); + } + + static Distance real(double distance) { + return new Distance(false, distance); + } + + @Override + public int compareTo(Distance o) { + if (o.infinite && this.infinite || (!o.infinite && !this.infinite && o.distance == this.distance)) { + return 0; + } + + if (o.infinite || (!this.infinite && this.distance < o.distance)) { + return -1; + } + + return 1; + } + } + + final static class Node { + private final String name; + private final double positionX; + private final double positionY; + private final Map edges; + + Node(String name, double positionX, double positionY) { + this.name = name; + this.positionX = positionX; + this.positionY = positionY; + this.edges = new HashMap<>(); + } + + String getName() { + return name; + } + + Distance euqlideanDistanceTo(Node o) { + return Distance.real(Math.sqrt(Math.pow(positionX - o.positionX, 2) + Math.pow(positionY - o.positionY, 2))); + } + } +} + +public class AStarPathfinding { + public static void main(String args[]) { + (new Graph()) + .add(new Graph.Node("A", 1, 4)) + .add(new Graph.Node("B", 1, 3)) + .add(new Graph.Node("C", 2, 3)) + .add(new Graph.Node("D", 3, 4)) + .add(new Graph.Node("E", 1, 2)) + .add(new Graph.Node("F", 3, 2)) + .add(new Graph.Node("G", 2, 1)) + .add(new Graph.Node("H", 1, 0)) + .add(new Graph.Node("I", 0, 2)) + .add(new Graph.Node("J", 0, 0)) + .edge("A", "B", 1.1) + .edge("A", "C", 1.47) + .edge("A", "D", 2.2) + .edge("C", "E", 1.43) + .edge("D", "F", 2.8) + .edge("E", "I", 1.01) + .edge("I", "J", 1.1) + .edge("J", "H", 1.12) + .edge("E", "G", 3.44) + .edge("F", "G", 1.44) + .edge("H", "G", 1.42) + .findShortestPathUsingAStar("A", "H") + .stream() + .map(Graph.Node::getName) + .forEach(name -> System.out.println("Route step: " + name)); + ; + } +} From da262ebb7cba9fe4cb7967fd2cd059c6b982c076 Mon Sep 17 00:00:00 2001 From: Rupali Kavale <30548190+coderquill@users.noreply.github.com> Date: Fri, 5 Oct 2018 01:55:15 +0530 Subject: [PATCH 26/46] Added program to implement binary tree creation. --- data-structures/BinaryTree.java | 67 +++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 data-structures/BinaryTree.java diff --git a/data-structures/BinaryTree.java b/data-structures/BinaryTree.java new file mode 100644 index 0000000..436c047 --- /dev/null +++ b/data-structures/BinaryTree.java @@ -0,0 +1,67 @@ +/* Class containing left and right child of current + node and key value*/ +class Node +{ + int key; + Node left, right; + + public Node(int item) + { + key = item; + left = right = null; + } +} + +// A Java program to make Binary Tree +class BinaryTree +{ + // Root of Binary Tree + Node root; + + // Constructors + BinaryTree(int key) + { + root = new Node(key); + } + + BinaryTree() + { + root = null; + } + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + + /*create root*/ + tree.root = new Node(1); + + /* following is the tree after above statement + + 1 + / \ + null null */ + + tree.root.left = new Node(2); + tree.root.right = new Node(3); + + /* 2 and 3 become left and right children of 1 + 1 + / \ + 2 3 + / \ / \ + null null null null */ + + + tree.root.left.left = new Node(4); + /* 4 becomes left child of 2 + 1 + / \ + 2 3 + / \ / \ + 4 null null null + / \ + null null + */ + } +} From 924e6d91aeca77445617a178414a63d4d40d5503 Mon Sep 17 00:00:00 2001 From: Anwar Rafiq shaikh Date: Fri, 5 Oct 2018 23:12:49 +0530 Subject: [PATCH 27/46] MaxHeap.java --- MaxHeap.java | 152 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 MaxHeap.java diff --git a/MaxHeap.java b/MaxHeap.java new file mode 100644 index 0000000..ac883af --- /dev/null +++ b/MaxHeap.java @@ -0,0 +1,152 @@ +import java.util.*; +import java.io.*; + + +abstract class Heap{ + protected int capacity; + protected int size; + protected int []items; + + public Heap() + { + this.capacity = 10; + this.size = 0; + this.items = new int[capacity]; + } + + public int getLeftChildIndex(int parentindex){ + return 2*parentindex+1; + } + + public int getRightChildIndex(int parentindex){ + return 2*parentindex+2; + } + + public int getParentIndex(int childIndex){ + return (childIndex-1)/2; + } + + public boolean hasLeftChild(int parentindex) + { + return getLeftChildIndex(parentindex) < size; + } + + + public boolean hasRightChild(int parentindex) + { + return getRightChildIndex(parentindex) < size; + } + + public boolean hasParent(int index){ + return getParentIndex(index) >= 0; + } + + public int leftChild(int parentindex){ + return items[getLeftChildIndex(parentindex)]; + } + + public int rightChild(int parentindex){ + return items[getRightChildIndex(parentindex)]; + } + + public int parent(int index) + { + return items[getParentIndex(index)]; + } + + public void swap(int indexone,int indextwo){ + int temp = items[indexone]; + items[indexone] = items[indextwo]; + items[indextwo] = temp; + } + + public void add(int item) + { + items[size] = item; + size++; + heapifyUp(); + } + public void isEmpty(String name) + { + if(size == 0) + { + System.out.println(name+"cant poll"); + } + } + + public int poll() + { + isEmpty("its empty"); + + int item = items[0]; + items[0] = items[size-1]; + size--; + + heapifyDown(); + return item; + } + + public void print() + { + for(int i=0;i leftChild(index)) + { + smallerChildIndex = getRightChildIndex(index); + } + + if(items[index] > items[smallerChildIndex]) + { + break; + } + else{ + swap(index,smallerChildIndex); + } + index = smallerChildIndex; + } + } + + + public void heapifyUp() + { + int index = size - 1; + while(hasParent(index) && parent(index) < items[index]){ + swap(getParentIndex(index),index); + index = getParentIndex(index); + } + } + + public static void main(String []args) + { + Scanner ob = new Scanner(System.in); + int n = ob.nextInt(); + Heap myHeap = new MaxHeap(); + for(int i=0;i Date: Sat, 6 Oct 2018 00:27:50 +0530 Subject: [PATCH 28/46] Added Selection Sort --- sorting/SelectionSort.java | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 sorting/SelectionSort.java diff --git a/sorting/SelectionSort.java b/sorting/SelectionSort.java new file mode 100644 index 0000000..8358d56 --- /dev/null +++ b/sorting/SelectionSort.java @@ -0,0 +1,51 @@ +package demos; + +import java.util.Scanner; + +public class SelectionSort { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner sc=new Scanner(System.in);//user input using scanner + System.out.println("Enter the size of the array");//taking size of the array from user + int size=sc.nextInt(); + + int array[]=new int[size];//declaring array of n elements to be sorted + System.out.println("Enter"+ size + "elements to sort"); + for(int i=0;iarray[j])//if i'th element of array is greater than j'th element swap the elements + { + int temp=array[i]; + array[i]=array[j]; + array[j]=temp; + } + } + } + + System.out.println("Array after sorting"); + for(int i=0;i Date: Sat, 6 Oct 2018 00:58:48 +0000 Subject: [PATCH 29/46] Java linear search --- data-structures/LinearSearch.java | 45 +++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 data-structures/LinearSearch.java diff --git a/data-structures/LinearSearch.java b/data-structures/LinearSearch.java new file mode 100644 index 0000000..1753500 --- /dev/null +++ b/data-structures/LinearSearch.java @@ -0,0 +1,45 @@ +/* + Program to find a particular key in the array (Linear-search) +*/ + +import java.util.Scanner; + +class LinearSearch{ + public static void main(String args[]){ + Scanner sc = new Scanner(System.in); + System.out.println("How many elements the array have?"); + System.out.print("Answer : "); + try{ + int[] arr = new int[sc.nextInt()]; + System.out.println("Enter elements one by one"); + for(int i = 0 ; i < arr.length; i++){ + System.out.print("Enter arr["+i+"] : "); + arr[i] = sc.nextInt(); + } + System.out.print("Enter the key you want to find : "); + int index = searchForKey(arr, sc.nextInt()); + if(index == -1){ + System.out.println("Sorry! Key is not in the array"); + }else{ + System.out.println("Key found on index -> "+index); + } + }catch(Exception e){ + System.out.println(e); + } + } + + public static int searchForKey(int[] arr, int key){ + /* + This function looks for the key in the array and returns index when key found and -1 if key is not in the array. + */ + for(int i=0; i < arr.length; i++){ + // Searching elements one by one + if(arr[i] == key){ + //returns index if found + return i; + } + } + //if failed to find key return -1 + return -1; + } +} \ No newline at end of file From 104811b8da347771ed5775f6aa5215d9b49fd766 Mon Sep 17 00:00:00 2001 From: joao-vieira Date: Fri, 5 Oct 2018 21:37:48 -0300 Subject: [PATCH 30/46] Create math directory and recursive factorial --- math/RecursiveFactorial.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 math/RecursiveFactorial.java diff --git a/math/RecursiveFactorial.java b/math/RecursiveFactorial.java new file mode 100644 index 0000000..1b01a54 --- /dev/null +++ b/math/RecursiveFactorial.java @@ -0,0 +1,20 @@ +package testes; +/** + * Java implementation of recursive factorial + * @author @joao-vieira + */ + +public class RecursiveFactorial { + + public int recursiveFactorial(int n) { + if(n <= 1) return 1; + return n * recursiveFactorial(n-1); + } + + public static void main(String[] args) { + // Test + int number = 3; + System.out.println(number + "! = " + new RecursiveFactorial().recursiveFactorial(number)); + } + +} From 4cab31fb375dced00aba5e80a0fad6bf0584daeb Mon Sep 17 00:00:00 2001 From: Rimjhim28 Date: Sun, 7 Oct 2018 00:26:26 +0530 Subject: [PATCH 31/46] Added Matrix Chain Multiplication --- .../MatrixChainMultiplication.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 dynamic-programming/MatrixChainMultiplication.java diff --git a/dynamic-programming/MatrixChainMultiplication.java b/dynamic-programming/MatrixChainMultiplication.java new file mode 100644 index 0000000..6d43ecc --- /dev/null +++ b/dynamic-programming/MatrixChainMultiplication.java @@ -0,0 +1,45 @@ +// Dynamic Programming Python implementation of Matrix +// Chain Multiplication. +public class MatrixChainMultiplication { +// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n + static int MatrixChainOrder(int p[], int n) { + /* For simplicity of the program, one extra row and one + extra column are allocated in m[][]. 0th row and 0th + column of m[][] are not used */ + int m[][] = new int[n][n]; + + int i, j, k, L, q; + + /* m[i,j] = Minimum number of scalar multiplications needed + to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where + dimension of A[i] is p[i-1] x p[i] */ + + // cost is zero when multiplying one matrix. + for (i = 1; i < n; i++) + m[i][i] = 0; + + // L is chain length. + for (L=2; L Date: Mon, 8 Oct 2018 16:44:03 +0530 Subject: [PATCH 32/46] Add BinarySearchRecursive.java A Recursive implementation of the Binary Search Algorithm in Java. Searches a given element in a sorted list/array of data. --- searches/BinarySearchRecursive.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 searches/BinarySearchRecursive.java diff --git a/searches/BinarySearchRecursive.java b/searches/BinarySearchRecursive.java new file mode 100644 index 0000000..9faf7b3 --- /dev/null +++ b/searches/BinarySearchRecursive.java @@ -0,0 +1,28 @@ +public class BinarySearchRecursive { + + public static int binarySearch(int[] arr, int toSearch, int start, int end) { + if (end < start) { + return -1; + } + int mid = (start + end) / 2; + if (arr[mid] > toSearch) { + return binarySearch(arr, toSearch, start, mid - 1); + } else if (arr[mid] < toSearch) { + return binarySearch(arr, toSearch, mid + 1, end); + } + return mid; + } + + public static void main(String[] args) { + int[] arr = {1, 5, 6, 7, 8, 11}; + int toSearch = 8; + + int index = binarySearch(arr, toSearch, 0, arr.length); + + if (index == -1) { + System.out.println(toSearch + " not found"); + } else { + System.out.println(toSearch + " found at index " + index); + } + } +} \ No newline at end of file From b460f83157e1051a07ee03f29e85bed4fe00e1b7 Mon Sep 17 00:00:00 2001 From: dafenix Date: Fri, 26 Oct 2018 21:26:19 +0200 Subject: [PATCH 33/46] levenshtein algorithm --- strings/LevenshteinDistance.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 strings/LevenshteinDistance.java diff --git a/strings/LevenshteinDistance.java b/strings/LevenshteinDistance.java new file mode 100644 index 0000000..433efc8 --- /dev/null +++ b/strings/LevenshteinDistance.java @@ -0,0 +1,31 @@ +// Source: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java +public class LevenshteinDistance { + private static int minimum(int a, int b, int c) { + return Math.min(Math.min(a, b), c); + } + + + public static int computeLevenshteinDistance(CharSequence lhs, CharSequence rhs) { + int[][] distance = new int[lhs.length() + 1][rhs.length() + 1]; + + for (int i = 0; i <= lhs.length(); i++) + distance[i][0] = i; + for (int j = 1; j <= rhs.length(); j++) + distance[0][j] = j; + + for (int i = 1; i <= lhs.length(); i++) + for (int j = 1; j <= rhs.length(); j++) + distance[i][j] = minimum( + distance[i - 1][j] + 1, + distance[i][j - 1] + 1, + distance[i - 1][j - 1] + ((lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1)); + + return distance[lhs.length()][rhs.length()]; + } + // Driver method to test above + public static void main(String args[]){ + System.out.println("Distance from 'stull' to 'still' is :"+ LevenshteinDistance.computeLevenshteinDistance("stull", "still")); + System.out.println("Distance from 'stull' to 'steal' is :"+ LevenshteinDistance.computeLevenshteinDistance("stull", "steal")); + System.out.println("Distance from 'skill' to 'steal' is :"+ LevenshteinDistance.computeLevenshteinDistance("skill", "steal")); + } +} \ No newline at end of file From f0e578640ae996e90ff7995a760f4f612b92782f Mon Sep 17 00:00:00 2001 From: "ramona.burger" Date: Thu, 3 Oct 2019 00:46:21 +0200 Subject: [PATCH 34/46] add MinMax Search --- sorting/MinMaxSearch.java | 53 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 sorting/MinMaxSearch.java diff --git a/sorting/MinMaxSearch.java b/sorting/MinMaxSearch.java new file mode 100644 index 0000000..4892b90 --- /dev/null +++ b/sorting/MinMaxSearch.java @@ -0,0 +1,53 @@ +public class MinMaxSearch { + + public MinMaxSearch(){ + + } + + + public int[] searchMinMax(int[] in) { + int n = in.length; + int j = 0; + int min; + int max; + int count = 0; + if (n % 2 == 1) { + j = j - 1; + min = in[0]; + max = in[0]; + count = count + 1; + } else if (in[0] < in[1]) { + min = in[0]; + max = in[1]; + count = count + 2; + } else { + min = in[1]; + max = in[0]; + count = count + 2; + } + for (int i = 1; i <= ((n - 1) / 2); i++) { + if (in[j + 2 * i] <= in[j + 2 * i + 1]) { + if (in[j + 2 * i] < min) { + min = in[j + 2 * i]; + } + if (in[j + 2 * i + 1] > max) { + max = in[j + 2 * i + 1]; + } + count = count + 3; + } else { + if (in[j + 2 * i + 1] < min) { + min = in[j + 2 * i + 1]; + } + if (in[j + 2 * i] > max) { + max = in[j + 2 * i]; + } + count = count + 3; + } + } + + int[] MinMaxC = { min, max, count }; + return MinMaxC; + + } + +} From 7857f97d14fef02625a264da3fc4ab136f82ff9c Mon Sep 17 00:00:00 2001 From: "ramona.burger" Date: Sat, 5 Oct 2019 13:23:53 +0200 Subject: [PATCH 35/46] add HeapSort with min-heap --- sorting/HeapSortMinHeap.java | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 sorting/HeapSortMinHeap.java diff --git a/sorting/HeapSortMinHeap.java b/sorting/HeapSortMinHeap.java new file mode 100644 index 0000000..1e26659 --- /dev/null +++ b/sorting/HeapSortMinHeap.java @@ -0,0 +1,40 @@ +public class HeapSortMinHeap>{ + public T[] heapSort(T[] M) { + int n = M.length - 1; + for (int i = n / 2; i >= 0; i--) { + heapify(i, n, M); + } + for (int i = n; i > 0; i--) { + T h1 = M[0]; + T h2 = M[i]; + M[i] = h1; + M[0] = h2; + heapify(0, i - 1, M); + } + return M; + } + + public T[] heapify(int i, int r, T[] M) { + T a = M[i]; + int j = 2 * i; + while (j <= r) { + if (j < r && M[j + 1].compareTo(M[j]) < 0) { + j++; + } + if (a.compareTo(M[j]) > 0) { + M[i] = M[j]; + i = j; + j = 2 * i; + + } else { + j = r + 1; + } + } + M[i] = a; + return M; + } + + public void sort(T[] M) { + heapSort(M); + } +} From de7d9280ee417208cecd5e0bdad4a0cbdf55f380 Mon Sep 17 00:00:00 2001 From: "ramona.burger" Date: Sat, 5 Oct 2019 13:29:51 +0200 Subject: [PATCH 36/46] add non-recursive MergeSort --- sorting/MergeSortNonRecursive.java | 56 ++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 sorting/MergeSortNonRecursive.java diff --git a/sorting/MergeSortNonRecursive.java b/sorting/MergeSortNonRecursive.java new file mode 100644 index 0000000..b9aa73b --- /dev/null +++ b/sorting/MergeSortNonRecursive.java @@ -0,0 +1,56 @@ +public class NonRecursiveMergeSort> { + + public T[] MergeSort(T[] M) { + + int length = M.length; + int size = 1; + int p; + while (size < length) { + p = -1; + while (p + size < length) { + int left = p + 1; + int right = left + size - 1; + if (right + size <= length) { + p = right + size; + } else { + p = length; + } + merge(M, left, right, p); + } + size = size * 2; + } + + return M; + + } + + + public T[] merge(T[] M, int left, int right, int p) { + int i = left; + int j = right + 1; + int k = left; + T[] M2 = M.clone(); + for (int n = 0; n < M.length; n++) { + M2[n] = null; + } + while (i <= right && j <= p) { + if (M[i].compareTo(M[j]) <= 0) { + M2[k] = M[i]; + i = i + 1; + } else { + M2[k] = M[j]; + j = j + 1; + } + k = k + 1; + } + for (int h = i; h <= right; h++) { + M[k + (h - i)] = M[h]; + } + for (int h = left; h <= (k - 1); h++) { + M[h] = M2[h]; + } + return M; + + } + +} From d53bc7e9e49c5d9777f83553932ddcd87db73bb1 Mon Sep 17 00:00:00 2001 From: anahita-singla <54863407+anahita-singla@users.noreply.github.com> Date: Sun, 20 Oct 2019 13:41:12 +0530 Subject: [PATCH 37/46] Create ExponentialSearch --- searches/ExponentialSearch | 66 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 searches/ExponentialSearch diff --git a/searches/ExponentialSearch b/searches/ExponentialSearch new file mode 100644 index 0000000..1b01266 --- /dev/null +++ b/searches/ExponentialSearch @@ -0,0 +1,66 @@ +// C++ program to find an element x in a +// sorted array using Exponential search. +#include +using namespace std; + +int binarySearch(int arr[], int, int, int); + +// Returns position of first occurrence of +// x in array +int exponentialSearch(int arr[], int n, int x) +{ + // If x is present at firt location itself + if (arr[0] == x) + return 0; + + // Find range for binary search by + // repeated doubling + int i = 1; + while (i < n && arr[i] <= x) + i = i*2; + + // Call binary search for the found range. + return binarySearch(arr, i/2, min(i, n), x); +} + +// A recursive binary search function. It returns +// location of x in given array arr[l..r] is +// present, otherwise -1 +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) + { + int mid = l + (r - l)/2; + + // If the element is present at the middle + // itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then it + // can only be present n left subarray + if (arr[mid] > x) + return binarySearch(arr, l, mid-1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid+1, r, x); + } + + // We reach here when element is not present + // in array + return -1; +} + +// Driver code +int main(void) +{ + int arr[] = {2, 3, 4, 10, 40}; + int n = sizeof(arr)/ sizeof(arr[0]); + int x = 10; + int result = exponentialSearch(arr, n, x); + (result == -1)? printf("Element is not present in array") + : printf("Element is present at index %d", + result); + return 0; +} From 03b2195d24de8fb5754e9f8d2cf1251d042b074e Mon Sep 17 00:00:00 2001 From: anahita-singla <54863407+anahita-singla@users.noreply.github.com> Date: Sun, 20 Oct 2019 13:50:20 +0530 Subject: [PATCH 38/46] Update ExponentialSearch --- searches/ExponentialSearch | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/searches/ExponentialSearch b/searches/ExponentialSearch index 1b01266..b4487ea 100644 --- a/searches/ExponentialSearch +++ b/searches/ExponentialSearch @@ -3,11 +3,11 @@ #include using namespace std; -int binarySearch(int arr[], int, int, int); +int BinarySearch(int arr[], int, int, int); // Returns position of first occurrence of // x in array -int exponentialSearch(int arr[], int n, int x) +int ExponentialSearch(int arr[], int n, int x) { // If x is present at firt location itself if (arr[0] == x) @@ -20,13 +20,13 @@ int exponentialSearch(int arr[], int n, int x) i = i*2; // Call binary search for the found range. - return binarySearch(arr, i/2, min(i, n), x); + return BinarySearch(arr, i/2, min(i, n), x); } // A recursive binary search function. It returns // location of x in given array arr[l..r] is // present, otherwise -1 -int binarySearch(int arr[], int l, int r, int x) +int BinarySearch(int arr[], int l, int r, int x) { if (r >= l) { @@ -40,11 +40,11 @@ int binarySearch(int arr[], int l, int r, int x) // If element is smaller than mid, then it // can only be present n left subarray if (arr[mid] > x) - return binarySearch(arr, l, mid-1, x); + return BinarySearch(arr, l, mid-1, x); // Else the element can only be present // in right subarray - return binarySearch(arr, mid+1, r, x); + return BinarySearch(arr, mid+1, r, x); } // We reach here when element is not present @@ -58,7 +58,7 @@ int main(void) int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr)/ sizeof(arr[0]); int x = 10; - int result = exponentialSearch(arr, n, x); + int result = ExponentialSearch(arr, n, x); (result == -1)? printf("Element is not present in array") : printf("Element is present at index %d", result); From fa9ec00689924694cf26303dd4d59e16023f9594 Mon Sep 17 00:00:00 2001 From: anahita-singla <54863407+anahita-singla@users.noreply.github.com> Date: Sun, 20 Oct 2019 13:54:39 +0530 Subject: [PATCH 39/46] Update ExponentialSearch --- searches/ExponentialSearch | 93 +++++++++++++------------------------- 1 file changed, 32 insertions(+), 61 deletions(-) diff --git a/searches/ExponentialSearch b/searches/ExponentialSearch index b4487ea..b136ffa 100644 --- a/searches/ExponentialSearch +++ b/searches/ExponentialSearch @@ -1,66 +1,37 @@ -// C++ program to find an element x in a -// sorted array using Exponential search. -#include -using namespace std; +import java.util.Arrays; -int BinarySearch(int arr[], int, int, int); - -// Returns position of first occurrence of -// x in array -int ExponentialSearch(int arr[], int n, int x) -{ - // If x is present at firt location itself - if (arr[0] == x) - return 0; - - // Find range for binary search by - // repeated doubling - int i = 1; - while (i < n && arr[i] <= x) - i = i*2; - - // Call binary search for the found range. - return BinarySearch(arr, i/2, min(i, n), x); -} - -// A recursive binary search function. It returns -// location of x in given array arr[l..r] is -// present, otherwise -1 -int BinarySearch(int arr[], int l, int r, int x) +class ExponentialSearch { - if (r >= l) + // Returns position of first occurrence of + // x in array + static int exponentialSearch(int arr[], + int n, int x) { - int mid = l + (r - l)/2; - - // If the element is present at the middle - // itself - if (arr[mid] == x) - return mid; - - // If element is smaller than mid, then it - // can only be present n left subarray - if (arr[mid] > x) - return BinarySearch(arr, l, mid-1, x); - - // Else the element can only be present - // in right subarray - return BinarySearch(arr, mid+1, r, x); + // If x is present at firt location itself + if (arr[0] == x) + return 0; + + // Find range for binary search by + // repeated doubling + int i = 1; + while (i < n && arr[i] <= x) + i = i*2; + + // Call binary search for the found range. + return Arrays.binarySearch(arr, i/2, + Math.min(i, n), x); + } + + // Driver code + public static void main(String args[]) + { + int arr[] = {2, 3, 4, 10, 40}; + int x = 10; + int result = exponentialSearch(arr, arr.length, x); + + System.out.println((result < 0) ? + "Element is not present in array" : + "Element is present at index " + + result); } - - // We reach here when element is not present - // in array - return -1; -} - -// Driver code -int main(void) -{ - int arr[] = {2, 3, 4, 10, 40}; - int n = sizeof(arr)/ sizeof(arr[0]); - int x = 10; - int result = ExponentialSearch(arr, n, x); - (result == -1)? printf("Element is not present in array") - : printf("Element is present at index %d", - result); - return 0; } From 6d5b4f5ea712b62e236dca28388bfc9149775803 Mon Sep 17 00:00:00 2001 From: anahita-singla <54863407+anahita-singla@users.noreply.github.com> Date: Sun, 20 Oct 2019 15:06:08 +0530 Subject: [PATCH 40/46] Update and rename ExponentialSearch to exponential_search.java --- searches/{ExponentialSearch => exponential_search.java} | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) rename searches/{ExponentialSearch => exponential_search.java} (87%) diff --git a/searches/ExponentialSearch b/searches/exponential_search.java similarity index 87% rename from searches/ExponentialSearch rename to searches/exponential_search.java index b136ffa..f7571be 100644 --- a/searches/ExponentialSearch +++ b/searches/exponential_search.java @@ -1,10 +1,10 @@ import java.util.Arrays; -class ExponentialSearch +class Exponential { // Returns position of first occurrence of // x in array - static int exponentialSearch(int arr[], + static int Exponential(int arr[], int n, int x) { // If x is present at firt location itself @@ -27,7 +27,7 @@ public static void main(String args[]) { int arr[] = {2, 3, 4, 10, 40}; int x = 10; - int result = exponentialSearch(arr, arr.length, x); + int result = Exponential(arr, arr.length, x); System.out.println((result < 0) ? "Element is not present in array" : From 0197663823473185c636cadcc59df9b92df64198 Mon Sep 17 00:00:00 2001 From: "Aanchal.Sharma" Date: Mon, 28 Oct 2019 02:28:28 +0530 Subject: [PATCH 41/46] Working of TreeMap in Java has been added --- data-structures/TreeMap_Implementation.java | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 data-structures/TreeMap_Implementation.java diff --git a/data-structures/TreeMap_Implementation.java b/data-structures/TreeMap_Implementation.java new file mode 100644 index 0000000..5d1c54d --- /dev/null +++ b/data-structures/TreeMap_Implementation.java @@ -0,0 +1,62 @@ +import java.util.Comparator; +import java.util.SortedMap; +import java.util.TreeMap; + +class TreeMap_Implementation { + + + //A TreeMap is a map implementation where they are always sorted based on the natural ordering of the keys, + // or based on a custom Comparator that you can provide at the time of creation of the TreeMap. + + // + public static void main(String[] args) { + // Creating a TreeMap + SortedMap names = new TreeMap<>(); + + + // Adding new key-value pairs to a TreeMap + names.put("Aanchal", "girl"); + names.put("Rahul", "boy"); + names.put("Arjun", "boy"); + names.put("Karen", "girl"); + names.put("Salman", "boy"); + + // Printing the TreeMap (Output will be sorted based on keys) + System.out.println(names); + + System.out.println(((TreeMap) names).firstEntry()); + + System.out.print(((TreeMap) names).lastEntry()); + + + SortedMap names_2 = new TreeMap<>(new Comparator() { + @Override + public int compare(String s1, String s2) { + return s2.compareTo(s1); + } + }); + + // Adding new key-value pairs to a TreeMap + names_2.put("Aanchal", "girl"); + names_2.put("Rahul", "boy"); + names_2.put("Arjun", "boy"); + names_2.put("Karen", "girl"); + names_2.put("Salman", "boy"); + + // Printing the TreeMap (The keys will be sorted based on the supplied comparator in descending order.) + System.out.println(names_2); + + System.out.println(((TreeMap) names_2).firstEntry()); + + System.out.print(((TreeMap) names_2).lastEntry()); + } + + } + + + /* Output: + {Aanchal=girl, Arjun=boy, Karen=girl, Rahul=boy, Salman=boy} + Aanchal=girl + Salman=boy{Salman=boy, Rahul=boy, Karen=girl, Arjun=boy, Aanchal=girl} + Salman=boy + Aanchal=girl*/ From 210f65c54e60681646296a06d3c79e6da9f959b5 Mon Sep 17 00:00:00 2001 From: Gabriel Einsdorf Date: Tue, 29 Oct 2019 14:21:45 +0100 Subject: [PATCH 42/46] Add BooleanBitSet --- bit-manipulation/BooleanBitSet.java | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 bit-manipulation/BooleanBitSet.java diff --git a/bit-manipulation/BooleanBitSet.java b/bit-manipulation/BooleanBitSet.java new file mode 100644 index 0000000..5736822 --- /dev/null +++ b/bit-manipulation/BooleanBitSet.java @@ -0,0 +1,56 @@ + +/** + * BooleanBitSet that encodes bits in longs, thus saving memory compared to a + * boolean[] array. + */ +public class BooleanBitSet { + + final long[] storage; + + public BooleanBitSet(int size) { + storage = new long[(int)Math.ceil(size / 64.0)]; + } + + public void set(int adress, boolean value){ + + // translate adress to holding long + int pos = (int)Math.floor(adress/ 64.0); + long holder = storage[pos]; + int offset = adress % 64; + + if(value){ + holder |= 1 << offset; + } else { + holder &= ~(1 << offset); + } + storage[pos] = holder; + } + + public boolean get(int adress){ + + long holder = storage[(int)Math.floor(adress/ 64.0)]; + int offset = adress % 64; + + return ((holder >> offset) & 1) == 1; + } + + public static void main(String...strings){ + + BooleanBitSet b = new BooleanBitSet(20); + b.set(0, true); + b.set(1, true); + b.set(3, true); + b.set(5, true); + + System.out.println(b.get(0)); + System.out.println(b.get(1)); + System.out.println(b.get(2)); + System.out.println(b.get(3)); + System.out.println(b.get(4)); + System.out.println(b.get(5)); + System.out.println(b.get(6)); + } + + + +} \ No newline at end of file From 39413d350fc3a14fbc2cf3de2983fa569b0bd4fc Mon Sep 17 00:00:00 2001 From: maannsaayyy <61039502+maannsaayyy@users.noreply.github.com> Date: Thu, 1 Oct 2020 14:24:14 +0530 Subject: [PATCH 43/46] Area Overload --- Pr3.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Pr3.java diff --git a/Pr3.java b/Pr3.java new file mode 100644 index 0000000..e234395 --- /dev/null +++ b/Pr3.java @@ -0,0 +1,22 @@ +/* wajp to create a class AreaOverload w two areas circle and rect */ + +class AreaOverload +{ +public double area(double radius) +{ + double ans=3.14159* radius*radius; + return ans; +} +public double area(double length,double width) +{ + double ans=length*width; + return ans; +}} +class Pr3 +{ +public static void main(String args[]) +{ +AreaOverload a=new AreaOverload(); +System.out.println("area of circle: "+a.area(1.5f,3.6f)); +System.out.println("area of rect: "+a.area(2.4f)); +}} \ No newline at end of file From 9e3b08ac5bd3fefe2a95e6e354831d061bb7092a Mon Sep 17 00:00:00 2001 From: "ramona.burger" Date: Mon, 5 Oct 2020 16:32:28 +0200 Subject: [PATCH 44/46] add heapSort --- sorting/heapSort.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 sorting/heapSort.java diff --git a/sorting/heapSort.java b/sorting/heapSort.java new file mode 100644 index 0000000..65bbe2f --- /dev/null +++ b/sorting/heapSort.java @@ -0,0 +1,39 @@ +public class HeapSort{ + + public T[] heapSort(T[] M) { + int n = M.length - 1; + for (int i = n / 2; i >= 0; i--) { + heapify(i, n, M); + } + for (int i = n; i > 0; i--) { + T h1 = M[0]; + T h2 = M[i]; + M[i] = h1; + M[0] = h2; + heapify(0, i - 1, M); + } + return M; + } + + public T[] heapify(int i, int r, T[] M) { + T a = M[i]; + int j = 2 * i; + while (j <= r) { + if (j < r && M[j + 1].compareTo(M[j]) > 0) { + j++; + } + if (a.compareTo(M[j]) < 0) { + M[i] = M[j]; + i = j; + j = 2 * i; + + } else { + j = r + 1; + } + } + M[i] = a; + return M; + } + + +} \ No newline at end of file From 44737f8f0be9ceec4387e220a0244cb9658fc5b8 Mon Sep 17 00:00:00 2001 From: Jan Tabacki Date: Wed, 7 Oct 2020 11:29:53 +0200 Subject: [PATCH 45/46] + implementation of generic InsertionSort.java --- sorting/InsertionSort.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 sorting/InsertionSort.java diff --git a/sorting/InsertionSort.java b/sorting/InsertionSort.java new file mode 100644 index 0000000..5e80491 --- /dev/null +++ b/sorting/InsertionSort.java @@ -0,0 +1,16 @@ +public class InsertionSort> { + public T[] Sort(T[] values) { + if (values.length > 0) { + T value = values[0]; + for (int i = 1; i < values.length; ++i) { + value = values[i]; + int j; + for (j = i - 1; j >= 0 && values[j].compareTo(value) > 0; --j) { + values[j + 1] = values[j]; + } + values[j + 1] = value; + } + } + return values; + } +} From 0534c14bf1bd10817fc35243d97ed6f7cadd34ca Mon Sep 17 00:00:00 2001 From: Jan Tabacki Date: Wed, 7 Oct 2020 11:51:50 +0200 Subject: [PATCH 46/46] + comments for InsertionSort --- sorting/InsertionSort.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sorting/InsertionSort.java b/sorting/InsertionSort.java index 5e80491..b9d6631 100644 --- a/sorting/InsertionSort.java +++ b/sorting/InsertionSort.java @@ -1,4 +1,15 @@ +/** +* Generic Insertion Sort +* @author Jan Tabacki +*/ + public class InsertionSort> { + + /** + * Sort + * @param T[] array of not sorted elements + * @return T[] array of sorted element + */ public T[] Sort(T[] values) { if (values.length > 0) { T value = values[0];