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/BinaryTrees-traversals/BinaryTree.java b/BinaryTrees-traversals/BinaryTree.java new file mode 100644 index 0000000..d69b9f1 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTree.java @@ -0,0 +1,58 @@ +/** + * Binary Tree Traversals implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + + +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/LowestCommonAncestor.java b/BinaryTrees-traversals/LowestCommonAncestor.java new file mode 100644 index 0000000..eb74e5b --- /dev/null +++ b/BinaryTrees-traversals/LowestCommonAncestor.java @@ -0,0 +1,50 @@ +/** + * To find Lowest Common Ancestor for a binary tree implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + +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/SubTree.java b/BinaryTrees-traversals/SubTree.java new file mode 100644 index 0000000..ed8d10d --- /dev/null +++ b/BinaryTrees-traversals/SubTree.java @@ -0,0 +1,64 @@ +/** + * Binary Tree Identical implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ +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/TreeNode.java b/BinaryTrees-traversals/TreeNode.java new file mode 100644 index 0000000..11ad3a0 --- /dev/null +++ b/BinaryTrees-traversals/TreeNode.java @@ -0,0 +1,40 @@ +/** + * Binary Tree Node implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + +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/TreeTraversal.java b/BinaryTrees-traversals/TreeTraversal.java new file mode 100644 index 0000000..9443295 --- /dev/null +++ b/BinaryTrees-traversals/TreeTraversal.java @@ -0,0 +1,33 @@ +/** + * Binary Tree Traversals implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + +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/TreeWithNoSiblings.java b/BinaryTrees-traversals/TreeWithNoSiblings.java new file mode 100644 index 0000000..d0dffb1 --- /dev/null +++ b/BinaryTrees-traversals/TreeWithNoSiblings.java @@ -0,0 +1,38 @@ +/** + * 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){ + 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); + } + +} 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= 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 - C Plus Plus Logo -
-
- -
-
-

All ▲lgorithms implemented in Java

- - - - - - - - -## Contents - -- [Arithmetic Analysis](arithmetic-analysis) -- [File Transfer Protocol](file-transfer-protocol) -- [Greedy Algorithms](greedy-algorithms) -- [Graphs](graphs) -- [Math](math) -- [Neural Network](neural-network) -- [Ciphers](ciphers) -- [Data Structures](data-structures) -- [Dynamic Programming](dynamic-programming) -- [Hashes](hashes) -- [Searches](searches) -- [Sorting](sorting) -- [Strings](strings) -- [Traversals](traversals) - - -## License - -This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) - -[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) - -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-license]: https://cdn.abranhe.com/projects/algorithms/mit-license.png diff --git a/algorithms/backtracking/CrosswordPuzzle.java b/algorithms/backtracking/CrosswordPuzzle.java new file mode 100644 index 0000000..89ff6ae --- /dev/null +++ b/algorithms/backtracking/CrosswordPuzzle.java @@ -0,0 +1,148 @@ +import java.util.*; + +public class CrosswordPuzzle { + public static void display(String[][] arr) { + for (int i = 0; i < arr.length; i++) { + for (int j = 0; j < arr[i].length; j++) { + System.out.print(arr[i][j]); + } + System.out.println(); + } + } + + public static void main(String[] args) { + Scanner scn = new Scanner(System.in); + + String[][] grid = new String[10][10]; + for (int i = 0; i < 10; i++) { + grid[i] = scn.nextLine().split(""); + } + + String[] words = scn.nextLine().split(";"); + + for (int i = 0; i < words.length; i++) { + if (puzzleSolved(grid, words, words[i], 0, 0)) { + break; + } + } + + scn.close(); + display(grid); + } + + public static boolean puzzleSolved(String[][] grid, String[] words, String word, int row, int col) { + + if (col >= grid.length) { + col = 0; + row += 1; + } + + while (row < grid.length && !grid[row][col].equals("-")) { + col += 1; + if (col >= grid.length) { + col = 0; + row += 1; + } + } + + if (row == grid.length) { + return false; + } + + boolean isPlacedHoz = false, isPlacedVer = false; + while (row - 1 >= 0 && !grid[row - 1][col].equals("+")) { + row -= 1; + } + + isPlacedVer = placeVertical(grid, row, col, word); + if (!isPlacedVer) { + while (col - 1 >= 0 && !grid[row][col - 1].equals("+")) { + col -= 1; + } + + isPlacedHoz = placeHorizontal(grid, row, col, word); + } + if (isPlacedVer || isPlacedHoz) { + String[] remainingWords = new String[words.length - 1]; + + if (remainingWords.length == 0) { + return true; + } + + int i = 0, j = 0; + while (i < words.length) { + if (!words[i].equals(word)) { + remainingWords[j] = words[i]; + j++; + } + i++; + } + + String pword = word; + for (int k = 0; k < remainingWords.length; k++) { + word = remainingWords[k]; + if (puzzleSolved(grid, remainingWords, word, row, col + 1)) { + return true; + } + } + if (isPlacedHoz) { + clearHorizontal(grid, row, col, pword); + } + if (isPlacedVer) { + clearVertical(grid, row, col, pword); + } + } + return false; + } + + public static boolean placeHorizontal(String[][] grid, int row, int col, String word) { + if (word.length() == 0 && (col == grid.length || grid[row][col].equals("+"))) { + return true; + } else if (col == grid.length || word.length() == 0) { + return false; + } + + if (grid[row][col].equals("-") || grid[row][col].equals(word.charAt(0) + "")) { + String prev = grid[row][col]; + grid[row][col] = word.charAt(0) + ""; + if (placeHorizontal(grid, row, col + 1, word.substring(1))) { + return true; + } + grid[row][col] = prev; + } + return false; + } + + public static boolean placeVertical(String[][] grid, int row, int col, String word) { + if (word.length() == 0 && (row == grid.length || grid[row][col].equals("+"))) { + return true; + } else if (row == grid.length || word.length() == 0) { + return false; + } + if (grid[row][col].equals("-") || grid[row][col].equals(word.charAt(0) + "")) { + String prev = grid[row][col]; + grid[row][col] = word.charAt(0) + ""; + if (placeVertical(grid, row + 1, col, word.substring(1))) { + return true; + } + grid[row][col] = prev; + } + return false; + } + + public static void clearHorizontal(String[][] grid, int row, int col, String word) { + int pcol = col; + while (pcol < grid.length && pcol < col + word.length()) { + grid[row][pcol] = "-"; + pcol++; + } + } + + public static void clearVertical(String[][] grid, int row, int col, String word) { + int prow = row; + while (prow < grid.length && prow < row + word.length()) { + grid[prow][col] = "-"; + prow++; + } + } +} diff --git a/ciphers/Ceasercipher.java b/algorithms/ciphers/Ceasercipher.java similarity index 87% rename from ciphers/Ceasercipher.java rename to algorithms/ciphers/Ceasercipher.java index 09fe8c9..bdc725b 100644 --- a/ciphers/Ceasercipher.java +++ b/algorithms/ciphers/Ceasercipher.java @@ -8,19 +8,18 @@ public class Ceasercipher { public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz"; - + /** * Encryption using plaintext and shiftkey + * * @param plainText * @param shiftKey * @return */ - public static String encrypt(String plainText, int shiftKey) - { + public static String encrypt(String plainText, int shiftKey) { plainText = plainText.toLowerCase(); String cipherText = ""; - for (int i = 0; i < plainText.length(); i++) - { + for (int i = 0; i < plainText.length(); i++) { int charPosition = ALPHABET.indexOf(plainText.charAt(i)); int keyVal = (shiftKey + charPosition) % 26; char replaceVal = ALPHABET.charAt(keyVal); @@ -31,20 +30,18 @@ public static String encrypt(String plainText, int shiftKey) /** * Decryption using encrypted value and shift key which used in encryption. + * * @param cipherText * @param shiftKey * @return */ - public static String decrypt(String cipherText, int shiftKey) - { + public static String decrypt(String cipherText, int shiftKey) { cipherText = cipherText.toLowerCase(); String plainText = ""; - for (int i = 0; i < cipherText.length(); i++) - { + for (int i = 0; i < cipherText.length(); i++) { int charPosition = ALPHABET.indexOf(cipherText.charAt(i)); int keyVal = (charPosition - shiftKey) % 26; - if (keyVal < 0) - { + if (keyVal < 0) { keyVal = ALPHABET.length() + keyVal; } char replaceVal = ALPHABET.charAt(keyVal); @@ -53,8 +50,7 @@ public static String decrypt(String cipherText, int shiftKey) return plainText; } - public static void main(String[] args) - { + public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the String for Encryption: "); String message = new String(); diff --git a/data-structures/DoubleLinkedListOfInteger.java b/algorithms/data-structures/DoubleLinkedListOfInteger.java similarity index 87% rename from data-structures/DoubleLinkedListOfInteger.java rename to algorithms/data-structures/DoubleLinkedListOfInteger.java index 26d8c9e..66cba76 100644 --- a/data-structures/DoubleLinkedListOfInteger.java +++ b/algorithms/data-structures/DoubleLinkedListOfInteger.java @@ -5,10 +5,11 @@ public class DoubleLinkedListOfInteger { private Node trailer; private int count; - private class Node { + private class Node { public Integer element; public Node next; public Node prev; + public Node(Integer e) { element = e; next = null; @@ -34,14 +35,14 @@ public void add(Integer element) { n.next = trailer; last.next = n; trailer.prev = n; - count++; + count++; } - + /** * Remove the first ocurence of a element at the list */ public boolean remove(Integer element) { - boolean achou = false; + boolean achou = false; Node aux = header.next; while (achou != true && aux != null) { @@ -56,7 +57,7 @@ public boolean remove(Integer element) { } return achou; } - + /** * Remove a element at index x */ @@ -82,7 +83,7 @@ public Integer remove(int index) { count--; return item; } - + /** * See's if the list have some element x */ @@ -96,7 +97,7 @@ public boolean contains(Integer element) { } return false; } - + /** * Return element at index x */ @@ -113,13 +114,13 @@ public Integer get(int index) { } return aux.element; } - + /** * Return index of the ocurence of the number x */ public int indexOf(Integer element) { Node aux = header.next; - for(int i=0; i= count)) { throw new IndexOutOfBoundsException(); } Node aux = header.next; - for(int i=0; i= size()) @@ -87,7 +78,6 @@ public Integer set(int index, Integer element) { Integer tmp = aux.element; aux.element = element; return tmp; - } /** @@ -131,8 +121,7 @@ public Integer removeByIndex(int index) { Node aux = head; if (index == 0) { - if (tail == head) // se tiver apenas um elemento - { + if (tail == head) { tail = null; } head = head.next; @@ -159,7 +148,7 @@ public Integer removeByIndex(int index) { * * @param element o elemento a ser buscado * @return o indice da primeira ocorrencia do elemento na lista, ou -1 se a - * lista nao contem o elemento + * lista nao contem o elemento */ public int indexOf(Integer element) { int index = 0; diff --git a/algorithms/data-structures/SegmentTree.java b/algorithms/data-structures/SegmentTree.java new file mode 100644 index 0000000..406fd52 --- /dev/null +++ b/algorithms/data-structures/SegmentTree.java @@ -0,0 +1,89 @@ +import java.util.*; +import java.lang.*; +import java.io.*; + +class SegmentTree { + int st[]; + + Segment(int []arr, int n) + { + int x = (int) Math.ceil((Math.log(n)/Math.log(2))); + int max_size = 2 *(int) (Math.pow(2,x) - 1); + st = new int[max_size]; + + constSegmentUtil(arr,0,n-1,0); + } + + int constSegmentUtil(int[] arr, int ss, int se, int si) { + if (ss == se) { + st[si] = arr[ss]; + return arr[ss]; + } + int mid = getMid(ss, se); + st[si] = max(constSegmentUtil(arr, ss, mid, 2 * si + 1), constSegmentUtil(arr, mid + 1, se, 2 * si + 2)); + return st[si]; + } + + int getMid(int s, int e) { + return s + (e - s) / 2; + } + + int max(int a, int b) { + if (a > b) { + return a; + } else { + return b; + } + } + + void print() { + for (int i = 0; i < st.length; i++) { + System.out.print(st[i]); + } + } + + int getMaxUtil(int ss, int se, int qs, int qe, int si) { + if (qs <= ss && qe >= se) { + return st[si]; + } + + if (se < qs || ss > qe) { + return 0; + } + + int mid = getMid(ss, se); + + return max(getMaxUtil(ss, mid, qs, qe, 2 * si + 1), getMaxUtil(mid + 1, se, qs, qe, 2 * si + 2)); + } + + int getMax(int n, int qs, int qe) { + + if (qs > qe || qs < 0 || qe > n - 1) { + return -1; + } + + return getMaxUtil(0, n - 1, qs, qe, 0); + } + + public static void main(String[] args) throws java.lang.Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(br.readLine());// for testcase + String[] temp = br.readLine().split(" ");// taking array as string + int[] arr = new int[t]; + for (int i = 0; i < t; i++) // to convert array of string to array of integers + { + arr[i] = Integer.parseInt(temp[i]); + } + Segment tree = new Segment(arr, arr.length); + // tree.print(); + int q = Integer.parseInt(br.readLine()); // no of queries + while (q-- != 0) { + String[] temp1 = br.readLine().split(" "); + int s = Integer.parseInt(temp1[0]); // q1 + int e = Integer.parseInt(temp1[1]); // q2 + + System.out.println(tree.getMax(arr.length, s - 1, e - 1)); // maximum in range [q1,q2] + // System.out.println(getMax(arr,n,s,e)); + } + } +} 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 51% rename from data-structures/UseStack.java rename to algorithms/data-structures/UseStack.java index c237e52..5acf6b8 100644 --- a/data-structures/UseStack.java +++ b/algorithms/data-structures/UseStack.java @@ -1,35 +1,31 @@ -class Stack -{ - int stcksize=100; +class Stack { + int stcksize = 100; int stck[] = new int[stcksize]; int tos; - Stack() - { - tos=-1; + + Stack() { + tos = -1; } - void push(int item) - { - if(tos==stcksize-1) + + void push(int item) { + if (tos == stcksize - 1) System.out.println("Stack Overflow"); else - stck[++tos]=item; + stck[++tos] = item; } - int pop() - { - if(tos<0) - { + + int pop() { + if (tos < 0) { System.out.println("Stack Underflow."); return 0; - } - else + } else return stck[tos--]; } } -public class UseStack -{ - public static void main(String args[]) - { - Stack s=new Stack(); + +public class UseStack { + public static void main(String args[]) { + Stack s = new Stack(); s.push(1); s.push(2); s.push(3); diff --git a/algorithms/dynamic-programming/EDIST.java b/algorithms/dynamic-programming/EDIST.java new file mode 100644 index 0000000..24913b3 --- /dev/null +++ b/algorithms/dynamic-programming/EDIST.java @@ -0,0 +1,47 @@ + +// A Naive recursive Java program to find minimum number +// operations to convert str1 to str2 +class EDIST { + static int min(int x, int y, int z) { + if (x <= y && x <= z) + return x; + if (y <= x && y <= z) + return y; + else + return z; + } + + static int editDist(String str1, String str2, int m, int n) { + // If first string is empty, the only option is to + // insert all characters of second string into first + if (m == 0) + return n; + + // If second string is empty, the only option is to + // remove all characters of first string + if (n == 0) + return m; + + // If last characters of two strings are same, nothing + // much to do. Ignore last characters and get count for + // remaining strings. + if (str1.charAt(m - 1) == str2.charAt(n - 1)) + return editDist(str1, str2, m - 1, n - 1); + + // If last characters are not same, consider all three + // operations on last character of first string, recursively + // compute minimum cost for all three operations and take + // minimum of three values. + return 1 + min(editDist(str1, str2, m, n - 1), // Insert + editDist(str1, str2, m - 1, n), // Remove + editDist(str1, str2, m - 1, n - 1) // Replace + ); + } + + public static void main(String args[]) { + String str1 = "sunday"; + String str2 = "saturday"; + + System.out.println(editDist(str1, str2, str1.length(), str2.length())); + } +} \ No newline at end of file diff --git a/algorithms/dynamic-programming/Kadane.java b/algorithms/dynamic-programming/Kadane.java new file mode 100644 index 0000000..eebc13e --- /dev/null +++ b/algorithms/dynamic-programming/Kadane.java @@ -0,0 +1,43 @@ +package AlgorithmsAndDS; + +public class Kadane { + + public static void main(String[] args) { + int[] arr = { 2, 3, -6, 1, 2, 3, -4, 5 }; + System.out.println(maximumSubArraySum(arr)); + // System.out.println(kadaneSum(arr)); + } + + public static int maximumSubArraySum(int[] arr) { + int osum = arr[0]; + int csum = arr[0]; + for (int i = 1; i < arr.length; i++) { + if (csum + arr[i] < arr[i]) { + csum = arr[i]; + } else { + csum += arr[i]; + } + if (csum > osum) { + osum = csum; + } + } + return osum; + } + + public static int kadaneSum(int[] arr) { + int osum = arr[0]; + int csum = arr[0]; + for (int i = 1; i < arr.length; i++) { + if (csum + arr[i] < arr[i]) { + csum = arr[i]; + } else { + csum += arr[i]; + } + if (csum > osum) { + osum = csum; + } + } + + return osum; + } +} diff --git a/algorithms/dynamic-programming/Knapsack.java b/algorithms/dynamic-programming/Knapsack.java new file mode 100644 index 0000000..83ae305 --- /dev/null +++ b/algorithms/dynamic-programming/Knapsack.java @@ -0,0 +1,38 @@ + +// A Dynamic Programming based solution for 0-1 Knapsack problem +class Knapsack { + + // A utility function that returns maximum of two integers + static int max(int a, int b) { + return (a > b) ? a : b; + } + + // Returns the maximum value that can be put in a knapsack of capacity W + static int knapSack(int W, int wt[], int val[], int n) { + int i, w; + int K[][] = new int[n + 1][W + 1]; + + // Build table K[][] in bottom up manner + for (i = 0; i <= n; i++) { + for (w = 0; w <= W; w++) { + if (i == 0 || w == 0) + K[i][w] = 0; + else if (wt[i - 1] <= w) + K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); + else + K[i][w] = K[i - 1][w]; + } + } + + return K[n][W]; + } + + // Driver program to test above function + public static void main(String args[]) { + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } +} \ No newline at end of file diff --git a/algorithms/dynamic-programming/LongestCommonSubsequence.java b/algorithms/dynamic-programming/LongestCommonSubsequence.java new file mode 100644 index 0000000..ebbe5d5 --- /dev/null +++ b/algorithms/dynamic-programming/LongestCommonSubsequence.java @@ -0,0 +1,43 @@ + +// Finding Longest Common Subsequence of Two Strings Using Dynamic Programming +import java.util.Scanner; + +public class LongestCommonSubsequence { + int lcs(char[] X, char[] Y, int m, int n) { + int DP[][] = new int[m + 1][n + 1]; + // Bottom-Up Approach for dp + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + if (i == 0 || j == 0) + DP[i][j] = 0; + else if (X[i - 1] == Y[j - 1]) + DP[i][j] = DP[i - 1][j - 1] + 1; + else + DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]); + } + } + return DP[m][n]; + } + + int max(int a, int b) { + if (a > b) + return a; + else + return b; + } + + public static void main(String[] args) { + LongestCommonSubsequence obj = new LongestCommonSubsequence(); + String s1 = "", s2 = ""; + Scanner scan = new Scanner(System.in); + System.out.println("Enter 1st String"); + s1 = scan.next(); + System.out.println("Enter 2nd String"); + s2 = scan.next(); + char[] X = s1.toCharArray(); + char[] Y = s2.toCharArray(); + int m = X.length; + int n = Y.length; + System.out.println("Length of Longest Common Subsequence is: " + obj.lcs(X, Y, m, n)); + } +} \ No newline at end of file diff --git a/dynamic-programming/MinCoinChange.java b/algorithms/dynamic-programming/MinCoinChange.java similarity index 86% rename from dynamic-programming/MinCoinChange.java rename to algorithms/dynamic-programming/MinCoinChange.java index a03e319..6098836 100644 --- a/dynamic-programming/MinCoinChange.java +++ b/algorithms/dynamic-programming/MinCoinChange.java @@ -24,9 +24,9 @@ static int minCoins(int coins[], int m, int V) { } public static void main(String args[]) { - int coins[] = {9, 6, 5, 1}; + int coins[] = { 9, 6, 5, 1 }; int m = coins.length; int value = 15; - System.out.println("Minimum coins is "+ minCoins(coins, m, value)); + System.out.println("Minimum coins is " + minCoins(coins, m, value)); } } diff --git a/algorithms/dynamic-programming/MinEditsToConvertStr1ToStr2.java b/algorithms/dynamic-programming/MinEditsToConvertStr1ToStr2.java new file mode 100644 index 0000000..82bdc85 --- /dev/null +++ b/algorithms/dynamic-programming/MinEditsToConvertStr1ToStr2.java @@ -0,0 +1,30 @@ +import java.util.Scanner; + +public class MinEditsToConvertStr1ToStr2 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner s = new Scanner(System.in); + int t = s.nextInt(); + while (t-- > 0) { + int p = s.nextInt(); + int q = s.nextInt(); + String str1 = s.next(); + String str2 = s.next(); + int[][] dp = new int[p + 1][q + 1]; + for (int i = 0; i <= p; i++) + dp[i][q] = p - i; + for (int j = 0; j <= q; j++) + dp[p][j] = q - j; + for (int i = p - 1; i >= 0; i--) + for (int j = q - 1; j >= 0; j--) { + if (str1.charAt(i) == str2.charAt(j)) + dp[i][j] = dp[i + 1][j + 1]; + else + dp[i][j] = 1 + Math.min(dp[i + 1][j + 1], Math.min(dp[i + 1][j], dp[i][j + 1])); + } + System.out.println(dp[0][0]); + } + } + +} diff --git a/algorithms/dynamic-programming/fibonacci.java b/algorithms/dynamic-programming/fibonacci.java new file mode 100644 index 0000000..ab5ce49 --- /dev/null +++ b/algorithms/dynamic-programming/fibonacci.java @@ -0,0 +1,28 @@ + +// Fibonacci Series using Dynamic Programming +class fibonacci { + static int fib(int n) { + /* Declare an array to store Fibonacci numbers. */ + int f[] = new int[n + 2]; // 1 extra to handle case, n = 0 + int i; + + /* 0th and 1st number of the series are 0 and 1 */ + f[0] = 0; + f[1] = 1; + + for (i = 2; i <= n; i++) { + /* + * Add the previous 2 numbers in the series and store it + */ + f[i] = f[i - 1] + f[i - 2]; + } + + return f[n]; + } + + public static void main(String args[]) { + int n = 9; + System.out.println(fib(n)); + } +} +/* This code is contributed by mokshagna517 */ diff --git a/graph/BinaryTree.java b/algorithms/graph/BinaryTree.java similarity index 97% rename from graph/BinaryTree.java rename to algorithms/graph/BinaryTree.java index ca0b7bb..b3b257c 100644 --- a/graph/BinaryTree.java +++ b/algorithms/graph/BinaryTree.java @@ -77,7 +77,7 @@ private void binaryTreeSort() { public class BinaryTree { public static void main(String[] args) { - int[] nums = {3, 2, 5, 6, 7, 1, 9, 0}; + int[] nums = { 3, 2, 5, 6, 7, 1, 9, 0 }; Tree tree = new Tree(); for (int n : nums) { tree.addValue(n); diff --git a/graphs/BFS.java b/algorithms/graphs/BFS.java similarity index 80% rename from graphs/BFS.java rename to algorithms/graphs/BFS.java index b37ba56..feb5718 100644 --- a/graphs/BFS.java +++ b/algorithms/graphs/BFS.java @@ -2,36 +2,30 @@ import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; - -public class BFS -{ - + +public class BFS { + private Queue queue; - - public BFS() - { + + public BFS() { queue = new LinkedList(); } - - public void bfs(int adjacency_matrix[][], int source) - { + + public void bfs(int adjacency_matrix[][], int source) { int number_of_nodes = adjacency_matrix[source].length - 1; - + int[] visited = new int[number_of_nodes + 1]; int i, element; - + visited[source] = 1; queue.add(source); - - while (!queue.isEmpty()) - { + + while (!queue.isEmpty()) { element = queue.remove(); i = element; System.out.print(i + "\t"); - while (i <= number_of_nodes) - { - if (adjacency_matrix[element][i] == 1 && visited[i] == 0) - { + while (i <= number_of_nodes) { + if (adjacency_matrix[element][i] == 1 && visited[i] == 0) { queue.add(i); visited[i] = 1; } @@ -39,34 +33,32 @@ public void bfs(int adjacency_matrix[][], int source) } } } - - public static void main(String... arg) - { + + public static void main(String... arg) { int number_no_nodes, source; Scanner scanner = null; - - try - { + + try { System.out.println("Enter the number of nodes in the graph"); scanner = new Scanner(System.in); number_no_nodes = scanner.nextInt(); - + int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1]; System.out.println("Enter the adjacency matrix"); for (int i = 1; i <= number_no_nodes; i++) for (int j = 1; j <= number_no_nodes; j++) adjacency_matrix[i][j] = scanner.nextInt(); - + System.out.println("Enter the source for the graph"); source = scanner.nextInt(); - + System.out.println("The BFS traversal of the graph is "); BFS bfs = new BFS(); bfs.bfs(adjacency_matrix, source); - - } catch (InputMismatchException inputMismatch) - { + + } catch (InputMismatchException inputMismatch) { System.out.println("Wrong Input Format"); } scanner.close(); } +} diff --git a/graphs/TopologicalSort.java b/algorithms/graphs/TopologicalSort.java similarity index 67% rename from graphs/TopologicalSort.java rename to algorithms/graphs/TopologicalSort.java index e93dfa6..ce6fbe4 100644 --- a/graphs/TopologicalSort.java +++ b/algorithms/graphs/TopologicalSort.java @@ -1,43 +1,35 @@ import java.util.InputMismatchException; import java.util.Scanner; import java.util.Stack; - -public class TopologicalSort -{ + +public class TopologicalSort { private Stack stack; - - public TopologicalSort() - { + + public TopologicalSort() { stack = new Stack(); } - - public int [] topological(int adjacency_matrix[][], int source) throws NullPointerException - { + + public int[] topological(int adjacency_matrix[][], int source) throws NullPointerException { int number_of_nodes = adjacency_matrix[source].length - 1; - int[] topological_sort = new int [number_of_nodes + 1]; + int[] topological_sort = new int[number_of_nodes + 1]; int pos = 1; - int j ; + int j; int visited[] = new int[number_of_nodes + 1]; int element = source; int i = source; visited[source] = 1; stack.push(source); - - while (!stack.isEmpty()) - { + + while (!stack.isEmpty()) { element = stack.peek(); - while (i <= number_of_nodes) - { - if (adjacency_matrix[element][i] == 1 && visited[i] == 1) - { - if (stack.contains(i)) - { + while (i <= number_of_nodes) { + if (adjacency_matrix[element][i] == 1 && visited[i] == 1) { + if (stack.contains(i)) { System.out.println("TOPOLOGICAL SORT NOT POSSIBLE"); return null; } - } - if (adjacency_matrix[element][i] == 1 && visited[i] == 0) - { + } + if (adjacency_matrix[element][i] == 1 && visited[i] == 0) { stack.push(i); visited[i] = 1; element = i; @@ -46,48 +38,43 @@ public TopologicalSort() } i++; } - j = stack.pop(); + j = stack.pop(); topological_sort[pos++] = j; i = ++j; } return topological_sort; - } - - public static void main(String...arg) - { + } + + public static void main(String... arg) { int number_no_nodes, source; Scanner scanner = null; - int topological_sort[] = null; - try - { + int topological_sort[] = null; + try { System.out.println("Enter the number of nodes in the graph"); scanner = new Scanner(System.in); number_no_nodes = scanner.nextInt(); - + int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1]; System.out.println("Enter the adjacency matrix"); - for (int i = 1; i <= number_no_nodes; i++) + for (int i = 1; i <= number_no_nodes; i++) for (int j = 1; j <= number_no_nodes; j++) adjacency_matrix[i][j] = scanner.nextInt(); - + System.out.println("Enter the source for the graph"); source = scanner.nextInt(); - + System.out.println("The Topological sort for the graph is given by "); TopologicalSort toposort = new TopologicalSort(); topological_sort = toposort.topological(adjacency_matrix, source); System.out.println(); - for (int i = topological_sort.length - 1; i > 0; i-- ) - { + for (int i = topological_sort.length - 1; i > 0; i--) { if (topological_sort[i] != 0) - System.out.print(topological_sort[i]+"\t"); - } - }catch(InputMismatchException inputMismatch) - { - System.out.println("Wrong Input format"); - }catch(NullPointerException nullPointer) - { - } + System.out.print(topological_sort[i] + "\t"); + } + } catch (InputMismatchException inputMismatch) { + System.out.println("Wrong Input format"); + } catch (NullPointerException nullPointer) { + } scanner.close(); } } diff --git a/algorithms/math/MatrixMultiply.java b/algorithms/math/MatrixMultiply.java new file mode 100644 index 0000000..359ba77 --- /dev/null +++ b/algorithms/math/MatrixMultiply.java @@ -0,0 +1,39 @@ + +public class MatrixMultiply { + + /** + * Multiples 2 2-dimensional matrices together given their dimensions are + * compatible + * + * @param mat_a A 2-Dimensional matrix to be multiplied + * @param mat_b A 2-Dimensional matrix to be multiplied + * @return The product of the two matrices if compatible dimensions, null + * otherwise + */ + public static double[][] matrixMultiply2D(double[][] mat_a, double[][] mat_b) { + int aRows = mat_a.length; + int aColumns = mat_a[0].length; + int bRows = mat_b.length; + int bColumns = mat_b[0].length; + + if (aColumns != bRows) + throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + "."); + + double[][] mat_result = new double[aRows][bColumns]; + for (int i = 0; i < aRows; i++) { + for (int j = 0; j < bColumns; j++) { + mat_result[i][j] = 0.00000; + } + } + + for (int i = 0; i < aRows; i++) { // aRow + for (int j = 0; j < bColumns; j++) { // bColumn + for (int k = 0; k < aColumns; k++) { // aColumn + mat_result[i][j] += mat_a[i][k] * mat_b[k][j]; + } + } + } + return mat_result; + } + +} diff --git a/algorithms/searches/BinarySearch.java b/algorithms/searches/BinarySearch.java new file mode 100644 index 0000000..0c14b81 --- /dev/null +++ b/algorithms/searches/BinarySearch.java @@ -0,0 +1,41 @@ + +// Java implementation of iterative Binary Search +class BinarySearch { + // Returns index of x if it is present in arr[], + // else return -1 + int binarySearch(int arr[], int x) { + int l = 0, r = arr.length - 1; + while (l <= r) { + int m = l + (r - l) / 2; + + // Check if x is present at mid + if (arr[m] == x) + return m; + + // If x greater, ignore left half + if (arr[m] < x) + l = m + 1; + + // If x is smaller, ignore right half + else + r = m - 1; + } + + // if we reach here, then element was + // not present + return -1; + } + + // Driver method to test above + public static void main(String args[]) { + BinarySearch ob = new BinarySearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, x); + if (result == -1) + System.out.println("Element not present"); + else + System.out.println("Element found at " + "index " + result); + } +} diff --git a/algorithms/searches/InterpolationSearch.java b/algorithms/searches/InterpolationSearch.java new file mode 100644 index 0000000..b23d310 --- /dev/null +++ b/algorithms/searches/InterpolationSearch.java @@ -0,0 +1,49 @@ + +// Java program to implement interpolation search + +class InterpolationSearch { + + // If x is present in arr[0..n-1], then returns + // index of it, else returns -1. + static int interpolationSearch(int x, int arr[]) { + // Find indexes of two corners + int lo = 0, hi = (arr.length - 1); + + // Since array is sorted, an element present + // in array must be in range defined by corner + while (lo <= hi && x >= arr[lo] && x <= arr[hi]) { + // Probing the position with keeping + // uniform distribution in mind. + int pos = lo + (((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); + + // Condition of target found + if (arr[pos] == x) + return pos; + + // If x is larger, x is in upper part + if (arr[pos] < x) + lo = pos + 1; + + // If x is smaller, x is in the lower part + else + hi = pos - 1; + } + return -1; + } + + // Driver method + public static void main(String[] args) { + int x = 18; // Element to be searched + // Array of items on which search will + // be conducted. + int arr[] = new int[] { 10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47 }; + + int index = interpolationSearch(x, arr); + + // If element was found + if (index != -1) + System.out.println("Element found at index " + index); + else + System.out.println("Element not found."); + } +} diff --git a/algorithms/searches/LinearSearch.java b/algorithms/searches/LinearSearch.java new file mode 100644 index 0000000..f5682cc --- /dev/null +++ b/algorithms/searches/LinearSearch.java @@ -0,0 +1,33 @@ +// Java code for linearly search x in arr[]. If x +// is present then return its location, otherwise +// return -1 + +class LinearSearch { + // This function returns index of element x in arr[] + 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 + if (arr[i] == x) + return i; + } + + // return -1 if the element is not found + 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); + } +} diff --git a/sorting/BubbleSort.java b/algorithms/sorting/BubbleSort.java similarity index 58% rename from sorting/BubbleSort.java rename to algorithms/sorting/BubbleSort.java index 316eb35..1655897 100644 --- a/sorting/BubbleSort.java +++ b/algorithms/sorting/BubbleSort.java @@ -4,36 +4,35 @@ * @author Carlos Abraham Hernandez (abraham@abranhe.com) */ - public class BubbleSort { - void bubbleSort(int arr[]){ - for (int i = 0; i < arr.length-1; i++) - for (int j = 0; j < arr.length-i-1; j++) - if (arr[j] > arr[j+1]){ + void bubbleSort(int arr[]) { + for (int i = 0; i < arr.length - 1; i++) + for (int j = 0; j < arr.length - i - 1; j++) + if (arr[j] > arr[j + 1]) { int temp = arr[j]; - arr[j] = arr[j+1]; - arr[j+1] = temp; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; } } // Function to print elements - void printArray(int arr[]){ - for (int i=0; i 0){ + for (int i = 0; i < temp.length; i++) { + while (temp[i] > 0) { result[index++] = i; temp[i]--; } } - + return result; } @@ -35,7 +35,7 @@ static void printArray(int[] nums) { } public static void main(String[] args) { - int[] nums = {3, 2, 5, 6, 7, 1, 9, 0, 8, 6}; + int[] nums = { 3, 2, 5, 6, 7, 1, 9, 0, 8, 6 }; nums = countingSort(nums, 10); printArray(nums); } diff --git a/algorithms/sorting/InsertionSort.java b/algorithms/sorting/InsertionSort.java new file mode 100644 index 0000000..95a357b --- /dev/null +++ b/algorithms/sorting/InsertionSort.java @@ -0,0 +1,46 @@ +/** + * Java implementation of insertion sort + * + * @author Andres Langberg + */ + +// Java program for implementation of Insertion Sort +public class InsertionSort { + /* Function to sort array using insertion sort */ + void sort(int arr[]) { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + + /* + * Move elements of arr[0..i-1], that are greater than key, to one position + * ahead of their current position + */ + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) { + int arr[] = { 12, 11, 13, 5, 6 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +} diff --git a/sorting/MergeSort.java b/algorithms/sorting/MergeSort.java similarity index 54% rename from sorting/MergeSort.java rename to algorithms/sorting/MergeSort.java index 6b2ce7b..aab719d 100644 --- a/sorting/MergeSort.java +++ b/algorithms/sorting/MergeSort.java @@ -1,3 +1,4 @@ + /** * Java implementation of merge sort * @@ -7,46 +8,44 @@ import java.util.Arrays; -public class MergeSort{ +public class MergeSort { - // Merge the two half into a sorted data. - public void merge(int arr[], int left, int middle, int right){ + // Merge the two half into a sorted data. + public void merge(int arr[], int left, int middle, int right) { int n1 = middle - left + 1; int n2 = right - middle; - int L[] = new int [n1]; - int R[] = new int [n2]; + int L[] = new int[n1]; + int R[] = new int[n2]; - for (int i=0; i= right) { + return; + } + + int i = left; + int j = right; + + int mid = (i + j) / 2; + // Pivot element + int v = arr[mid]; + + while (i < j) { + // Find element from the left side, which is equal or greater than pivot element + while (arr[i] < v) { + i++; + } + + // Find element from the right side, which is equal or less than pivot element + while (v < arr[j]) { + j--; + } + + // If such elements exist, perform swapping + if (i <= j) { + swap(arr, i, j); + i++; + j--; + } + } + + // Recursively sort left subarray + sort(arr, left, j); + // Recursively sort right subarray + sort(arr, i, right); + } + + /** + * Swaps two elements. + * + * @param arr array of elements + * @param i first index + * @param j second index + */ + private void swap(int[] arr, int i, int j) { + int buf = arr[i]; + arr[i] = arr[j]; + arr[j] = buf; + } + + /** + * Entry point, invokes sorting methods and prints resulting array. + * + * @param arr array to sort + */ + public void run(int[] arr) { + sort(arr, 0, arr.length - 1); + printArray(arr); + } + + /** + * Utility method to print array. + * + * @param arr array to print + */ + private void printArray(int[] arr) { + for (int i : arr) { + System.out.print(i + " "); + } + System.out.println(); + } + + /** + * {@code Main} method. Initializes {@link QuickSort} object and passes simple + * array to sort. + * + * @param args cmd arguments + */ + public static void main(String args[]) { + int arr[] = { 100, 19, 23, 1, 4, 23, 66 }; + new QuickSort().run(arr); + } +} \ No newline at end of file diff --git a/algorithms/sorting/SelectionSort.java b/algorithms/sorting/SelectionSort.java new file mode 100644 index 0000000..4b03964 --- /dev/null +++ b/algorithms/sorting/SelectionSort.java @@ -0,0 +1,29 @@ +/** + * Java implementation of merge sort + * + * @author Dimitris Glynatsis + * @email dim.glynatsis@gmail.com + */ + +public class SelectionSort { + static void selection(int[] a, int left, int right) { + for (int i = left; i < right; i++) { + int min = i; + for (int j = i + 1; j <= right; j++) + if (a[j] < a[min]) + min = j; + int temp = a[i]; + a[i] = a[min]; + a[min] = temp; + } + } + + public static void main(String[] args) { + int[] a = { 5, 4, 6, 1, 3, 8 }; + + SelectionSort s = new SelectionSort(); + s.selection(a, 0, a.length - 1); + for (int i = 0; i < a.length; i++) + System.out.println(a[i]); + } +} \ No newline at end of file diff --git a/algorithms/sorting/ShellSort.java b/algorithms/sorting/ShellSort.java new file mode 100644 index 0000000..ae61e18 --- /dev/null +++ b/algorithms/sorting/ShellSort.java @@ -0,0 +1,36 @@ +/** + * Java implementation of merge sort + * + * @author Dimitris Glynatsis + * @email dim.glynatsis@gmail.com + */ + +public class ShellSort { + + static void shell(int[] a) { + int l = 0, r = a.length - 1, h; + for (h = 0; h <= (r - 1) / 9; h = 3 * h + 1) + ; + for (; h > 0; h /= 3) + for (int i = l + h; i <= r; i++) { + int j = i, v = a[i]; + while (j >= l + h && v < a[j - h]) { + a[j] = a[j - h]; + j -= h; + } + a[j] = v; + } + } + + public static void main(String[] args) { + int[] a = { 5, 6, 4, 9, 13, 3, 7 }; + + ShellSort s = new ShellSort(); + + s.shell(a); + + for (int i = 0; i < a.length; i++) + System.out.println(a[i]); + } + +} \ No newline at end of file diff --git a/backtracking/CrosswordPuzzle.java b/backtracking/CrosswordPuzzle.java deleted file mode 100644 index 3fabeab..0000000 --- a/backtracking/CrosswordPuzzle.java +++ /dev/null @@ -1,148 +0,0 @@ -import java.io.*; -import java.util.*; - -public class CrosswordPuzzle { - public static void display(String[][] arr){ - for(int i = 0; i < arr.length; i++){ - for(int j = 0; j < arr[i].length; j++){ - System.out.print(arr[i][j]); - } - System.out.println(); - } - } - - public static void main(String[] args) { - Scanner scn = new Scanner(System.in); - - String[][] grid = new String[10][10]; - for(int i = 0; i < 10; i++){ - grid[i] = scn.nextLine().split(""); - } - - String[] words = scn.nextLine().split(";"); - - for(int i = 0; i < words.length; i++){ - if(puzzleSolved(grid, words, words[i], 0, 0)){ - break; - } - } - - display(grid); - } - - public static boolean puzzleSolved(String[][] grid, String[] words, String word, int row, int col){ - - if(col >= grid.length){ - col = 0; - row += 1; - } - - while(row < grid.length && !grid[row][col].equals("-")){ - col += 1; - if(col >= grid.length){ - col = 0; - row += 1; - } - } - - if(row == grid.length){ - return false; - } - - boolean isPlacedHoz = false, isPlacedVer = false; - while(row - 1 >= 0 && !grid[row - 1][col].equals("+")){ - row -= 1; - } - - isPlacedVer = placeVertical(grid, row, col, word); - if(!isPlacedVer){ - while(col - 1 >= 0 && !grid[row][col - 1].equals("+")){ - col -= 1; - } - - isPlacedHoz = placeHorizontal(grid, row, col, word); - } - if( isPlacedVer || isPlacedHoz){ - String[] remainingWords = new String[words.length - 1]; - - if(remainingWords.length == 0){ - return true; - } - - int i = 0, j = 0; - while(i < words.length){ - if(!words[i].equals(word)){ - remainingWords[j] = words[i]; - j++; - } - i++; - } - - String pword = word; - for(int k = 0; k < remainingWords.length; k++){ - word = remainingWords[k]; - if(puzzleSolved(grid, remainingWords, word, row, col + 1)){ - return true; - } - } - if(isPlacedHoz){ - clearHorizontal(grid, row, col, pword); - } - if(isPlacedVer){ - clearVertical(grid, row, col, pword); - } - } - return false; - } - - public static boolean placeHorizontal(String[][] grid, int row, int col, String word){ - if(word.length() == 0 && (col == grid.length || grid[row][col].equals("+"))){ - return true; - }else if(col == grid.length || word.length() == 0){ - return false; - } - - if(grid[row][col].equals("-") || grid[row][col].equals(word.charAt(0)+"")){ - String prev = grid[row][col]; - grid[row][col] = word.charAt(0) + ""; - if(placeHorizontal(grid, row, col + 1, word.substring(1))){ - return true; - } - grid[row][col] = prev; - } - return false; - } - - public static boolean placeVertical(String[][] grid, int row, int col,String word){ - if(word.length() == 0 && (row == grid.length || grid[row][col].equals("+"))){ - return true; - } else if(row == grid.length || word.length() == 0){ - return false; - } - if(grid[row][col].equals("-") || grid[row][col].equals(word.charAt(0)+"")){ - String prev = grid[row][col]; - grid[row][col] = word.charAt(0) + ""; - if(placeVertical(grid, row + 1, col, word.substring(1))){ - return true; - } - grid[row][col] = prev; - } - return false; - } - - public static void clearHorizontal(String[][] grid, int row, int col, String word){ - int pcol = col; - while(pcol < grid.length && pcol < col + word.length()){ - grid[row][pcol] = "-"; - pcol++; - } - } - - public static void clearVertical(String[][] grid, int row, int col, String word){ - int prow = row; - while(prow < grid.length && prow < row + word.length()){ - grid[prow][col] = "-"; - prow++; - } - } -} 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 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 + */ + } +} 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 diff --git a/data-structures/SegmentTree.java b/data-structures/SegmentTree.java deleted file mode 100644 index 0fb2f83..0000000 --- a/data-structures/SegmentTree.java +++ /dev/null @@ -1,101 +0,0 @@ -import java.util.*; -import java.lang.*; -import java.io.*; -class SegmentTree -{ - int st[]; - Segment(int []arr, int n) - { - int x = (int) Math.ceil((Math.log(n)/Math.log(2))); - int max_size = 2 *(int) (Math.pow(2,x) - 1); - st = new int[max_size]; - - constSegmentUtil(arr,0,n-1,0); - } - - int constSegmentUtil(int []arr, int ss,int se,int si) - { - if(ss == se) - { - st[si] = arr[ss]; - return arr[ss]; - } - int mid = getMid(ss,se); - st[si] = max(constSegmentUtil(arr,ss,mid,2*si+1),constSegmentUtil(arr,mid+1,se,2*si+2)); - return st[si]; - } - - int getMid(int s,int e) - { - return s + (e - s)/2; - } - - int max(int a,int b) - { - if(a > b) - { - return a; - } - else{ - return b; - } - } - - void print(){ - for (int i=0;i=se) - { - return st[si]; - } - - if(seqe) - { - return 0; - } - - int mid = getMid(ss,se); - - return max(getMaxUtil(ss,mid,qs,qe,2*si+1),getMaxUtil(mid+1,se,qs,qe,2*si+2)); - } - - - int getMax(int n,int qs,int qe){ - - if(qs > qe || qs < 0 || qe > n-1){ - return -1; - } - - return getMaxUtil(0,n-1,qs,qe,0); - } - - public static void main (String[] args) throws java.lang.Exception - { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - int t = Integer.parseInt(br.readLine());//for testcase - String []temp = br.readLine().split(" ");//taking array as string - int []arr = new int[t]; - for(int i=0;i 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*/ diff --git a/dynamic-programming/EDIST.java b/dynamic-programming/EDIST.java deleted file mode 100644 index 6c3c7dc..0000000 --- a/dynamic-programming/EDIST.java +++ /dev/null @@ -1,46 +0,0 @@ - -// A Naive recursive Java program to find minimum number -// operations to convert str1 to str2 -class EDIST -{ - static int min(int x,int y,int z) - { - if (x<=y && x<=z) return x; - if (y<=x && y<=z) return y; - else return z; - } - - static int editDist(String str1 , String str2 , int m ,int n) - { - // If first string is empty, the only option is to - // insert all characters of second string into first - if (m == 0) return n; - - // If second string is empty, the only option is to - // remove all characters of first string - if (n == 0) return m; - - // If last characters of two strings are same, nothing - // much to do. Ignore last characters and get count for - // remaining strings. - if (str1.charAt(m-1) == str2.charAt(n-1)) - return editDist(str1, str2, m-1, n-1); - - // If last characters are not same, consider all three - // operations on last character of first string, recursively - // compute minimum cost for all three operations and take - // minimum of three values. - return 1 + min ( editDist(str1, str2, m, n-1), // Insert - editDist(str1, str2, m-1, n), // Remove - editDist(str1, str2, m-1, n-1) // Replace - ); - } - - public static void main(String args[]) - { - String str1 = "sunday"; - String str2 = "saturday"; - - System.out.println( editDist( str1 , str2 , str1.length(), str2.length()) ); - } -} \ No newline at end of file diff --git a/dynamic-programming/Kadane.java b/dynamic-programming/Kadane.java deleted file mode 100644 index a2aa1a1..0000000 --- a/dynamic-programming/Kadane.java +++ /dev/null @@ -1,48 +0,0 @@ -package AlgorithmsAndDS; - -public class Kadane { - - public static void main(String[] args) { - int[] arr= {2,3,-6,1,2,3,-4,5}; - System.out.println(maximumSubArraySum(arr)); - //System.out.println(kadaneSum(arr)); - } - public static int maximumSubArraySum(int[] arr) { - int osum=arr[0]; - int csum=arr[0]; - for(int i=1;iosum) { - osum=csum; - } - } - return osum; - } - - - - - public static int kadaneSum(int[] arr) { - int osum=arr[0]; - int csum=arr[0]; - for(int i=1;iosum) { - osum=csum; - } - } - - return osum; - } -} diff --git a/dynamic-programming/Knapsack.java b/dynamic-programming/Knapsack.java deleted file mode 100644 index 0172762..0000000 --- a/dynamic-programming/Knapsack.java +++ /dev/null @@ -1,42 +0,0 @@ - -// A Dynamic Programming based solution for 0-1 Knapsack problem -class Knapsack -{ - - // A utility function that returns maximum of two integers - static int max(int a, int b) { return (a > b)? a : b; } - - // Returns the maximum value that can be put in a knapsack of capacity W - static int knapSack(int W, int wt[], int val[], int n) - { - int i, w; - int K[][] = new int[n+1][W+1]; - - // Build table K[][] in bottom up manner - for (i = 0; i <= n; i++) - { - for (w = 0; w <= W; w++) - { - if (i==0 || w==0) - K[i][w] = 0; - else if (wt[i-1] <= w) - K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); - else - K[i][w] = K[i-1][w]; - } - } - - return K[n][W]; - } - - - // Driver program to test above function - public static void main(String args[]) - { - int val[] = new int[]{60, 100, 120}; - int wt[] = new int[]{10, 20, 30}; - int W = 50; - int n = val.length; - System.out.println(knapSack(W, wt, val, n)); - } -} \ No newline at end of file diff --git a/dynamic-programming/LongestCommonSubsequence.java b/dynamic-programming/LongestCommonSubsequence.java deleted file mode 100644 index 9917ab2..0000000 --- a/dynamic-programming/LongestCommonSubsequence.java +++ /dev/null @@ -1,45 +0,0 @@ -// Finding Longest Common Subsequence of Two Strings Using Dynamic Programming -import java.util.Scanner; -public class LongestCommonSubsequence -{ - int lcs(char[] X, char[] Y, int m, int n) - { - int DP[][] = new int[m+1][n+1]; - // Bottom-Up Approach for dp - for(int i=0;i<=m;i++) - { - for(int j=0;j<=n;j++) - { - if(i==0 || j==0) - DP[i][j]=0; - else if(X[i-1]==Y[j-1]) - DP[i][j]=DP[i-1][j-1]+1; - else - DP[i][j] = max(DP[i-1][j], DP[i][j-1]); - } - } - return DP[m][n]; - } - int max(int a, int b) - { - if(a>b) - return a; - else - return b; - } - public static void main(String[] args) - { - LongestCommonSubsequence obj=new LongestCommonSubsequence(); - String s1="",s2=""; - Scanner scan=new Scanner(System.in); - System.out.println("Enter 1st String"); - s1=scan.next(); - System.out.println("Enter 2nd String"); - s2=scan.next(); - char[] X=s1.toCharArray(); - char[] Y=s2.toCharArray(); - int m=X.length; - int n=Y.length; - System.out.println("Length of Longest Common Subsequence is: "+obj.lcs(X,Y,m,n)); - } -} \ No newline at end of file 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; L0) - { - int p = s.nextInt(); - int q = s.nextInt(); - String str1 = s.next(); - String str2 = s.next(); - int[][] dp = new int[p+1][q+1]; - for(int i=0;i<=p;i++) - dp[i][q] = p-i; - for(int j=0;j<=q;j++) - dp[p][j] = q-j; - for(int i=p-1;i>=0;i--) - for(int j=q-1;j>=0;j--) - { - if(str1.charAt(i)==str2.charAt(j)) - dp[i][j] = dp[i+1][j+1]; - else - dp[i][j] = 1+Math.min(dp[i+1][j+1],Math.min(dp[i+1][j],dp[i][j+1])); - } - System.out.println(dp[0][0]); - } - } - -} diff --git a/dynamic-programming/fibonacci.java b/dynamic-programming/fibonacci.java deleted file mode 100644 index 161ba54..0000000 --- a/dynamic-programming/fibonacci.java +++ /dev/null @@ -1,31 +0,0 @@ - -// Fibonacci Series using Dynamic Programming -class fibonacci -{ - static int fib(int n) - { - /* Declare an array to store Fibonacci numbers. */ - int f[] = new int[n+2]; // 1 extra to handle case, n = 0 - int i; - - /* 0th and 1st number of the series are 0 and 1*/ - f[0] = 0; - f[1] = 1; - - for (i = 2; i <= n; i++) - { - /* Add the previous 2 numbers in the series - and store it */ - f[i] = f[i-1] + f[i-2]; - } - - return f[n]; - } - - public static void main (String args[]) - { - int n = 9; - System.out.println(fib(n)); - } -} -/* This code is contributed by mokshagna517 */ diff --git a/graph-algorithms/BellmanFord.java b/graph-algorithms/BellmanFord.java new file mode 100644 index 0000000..9a16e01 --- /dev/null +++ b/graph-algorithms/BellmanFord.java @@ -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(); + } +} diff --git a/graph-algorithms/DFS.java b/graph-algorithms/DFS.java new file mode 100644 index 0000000..ceefd1f --- /dev/null +++ b/graph-algorithms/DFS.java @@ -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(); + } +} diff --git a/graph-algorithms/Dijkstra.java b/graph-algorithms/Dijkstra.java new file mode 100644 index 0000000..682fb39 --- /dev/null +++ b/graph-algorithms/Dijkstra.java @@ -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(); + } +} 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)); + ; + } +} 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(); + } +} diff --git a/graph/DFS.java b/graph/DFS.java new file mode 100644 index 0000000..4faa384 --- /dev/null +++ b/graph/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(""); + } +} diff --git a/greedy-algorithms/HuffmanCoding.java b/greedy-algorithms/HuffmanCoding.java new file mode 100644 index 0000000..e2fa247 --- /dev/null +++ b/greedy-algorithms/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, ""); + } +} diff --git a/license b/license new file mode 100644 index 0000000..559a12b --- /dev/null +++ b/license @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.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 +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/math/MatrixMultiply.java b/math/MatrixMultiply.java deleted file mode 100644 index a666a41..0000000 --- a/math/MatrixMultiply.java +++ /dev/null @@ -1,40 +0,0 @@ - -public class MatrixMultiply { - - /** - * Multiples 2 2-dimensional matrices together given their dimensions are compatible - * @param mat_a A 2-Dimensional matrix to be multiplied - * @param mat_b A 2-Dimensional matrix to be multiplied - * @return The product of the two matrices if compatible dimensions, null otherwise - */ - public static double[][] matrixMultiply2D(double[][] mat_a, double[][] mat_b) - { - int aRows = mat_a.length; - int aColumns = mat_a[0].length; - int bRows = mat_b.length; - int bColumns = mat_b[0].length; - - if (aColumns != bRows) - throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + "."); - - double[][] mat_result = new double[aRows][bColumns]; - for (int i = 0; i < aRows; i++) { - for (int j = 0; j < bColumns; j++) { - mat_result[i][j] = 0.00000; - } - } - - for (int i = 0; i < aRows; i++) { // aRow - for (int j = 0; j < bColumns; j++) { // bColumn - for (int k = 0; k < aColumns; k++) { // aColumn - mat_result[i][j] += mat_a[i][k] * mat_b[k][j]; - } - } - } - return mat_result; - } - - -} - - 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 + } +} 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 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)); + } + +} diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..dd64172 --- /dev/null +++ b/readme.md @@ -0,0 +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 +

+
+ + + + + + +
+ +## See + +- [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) + + +## What is an algorithm? + +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. + +An algorithm should have three important characteristics to be considered valid: + +- **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. + +## Categories + +> Structure of The All ▲lgoritms project + +- [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) + +## [Artificial Intelligence](artificial-intelligence) + +- [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) + +## [Backtracking](backtracking) + +- [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) + +## [Bit Manipulation](bit-manipulation) + +- [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) + +## [Cellular Automaton](cellular-automaton) + +- [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) + +## [Computational Geometry](computational-geometry) + +- [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/) + +## [Cryptography](cryptography) + +- [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) + +- [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) + +## [Greedy Algorithms](greedy-algorithms) + +- [Activity Selection](greedy-algorithms) +- [Dijkstra Shortest Path](greedy-algorithms) +- [Egyptian Fraction](greedy-algorithms) + +## [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. + +
+ + + +
+
\ No newline at end of file diff --git a/searches/BinarySearch.java b/searches/BinarySearch.java deleted file mode 100644 index 79343fa..0000000 --- a/searches/BinarySearch.java +++ /dev/null @@ -1,46 +0,0 @@ - -// Java implementation of iterative Binary Search -class BinarySearch -{ - // Returns index of x if it is present in arr[], - // else return -1 - int binarySearch(int arr[], int x) - { - int l = 0, r = arr.length - 1; - while (l <= r) - { - int m = l + (r-l)/2; - - // Check if x is present at mid - if (arr[m] == x) - return m; - - // If x greater, ignore left half - if (arr[m] < x) - l = m + 1; - - // If x is smaller, ignore right half - else - r = m - 1; - } - - // if we reach here, then element was - // not present - return -1; - } - - // Driver method to test above - public static void main(String args[]) - { - BinarySearch ob = new BinarySearch(); - int arr[] = {2, 3, 4, 10, 40}; - int n = arr.length; - int x = 10; - int result = ob.binarySearch(arr, x); - if (result == -1) - System.out.println("Element not present"); - else - System.out.println("Element found at " + - "index " + result); - } -} 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 diff --git a/searches/InterpolationSearch.java b/searches/InterpolationSearch.java deleted file mode 100644 index 23886b1..0000000 --- a/searches/InterpolationSearch.java +++ /dev/null @@ -1,55 +0,0 @@ - -// Java program to implement interpolation search - -class InterpolationSearch -{ - - // If x is present in arr[0..n-1], then returns - // index of it, else returns -1. - static int interpolationSearch(int x, int arr[]) - { - // Find indexes of two corners - int lo = 0, hi = (arr.length - 1); - - // Since array is sorted, an element present - // in array must be in range defined by corner - while (lo <= hi && x >= arr[lo] && x <= arr[hi]) - { - // Probing the position with keeping - // uniform distribution in mind. - int pos = lo + (((hi-lo) / - (arr[hi]-arr[lo]))*(x - arr[lo])); - - // Condition of target found - if (arr[pos] == x) - return pos; - - // If x is larger, x is in upper part - if (arr[pos] < x) - lo = pos + 1; - - // If x is smaller, x is in the lower part - else - hi = pos - 1; - } - return -1; - } - - // Driver method - public static void main(String[] args) - { - int x = 18; // Element to be searched - // Array of items on which search will - // be conducted. - int arr[] = new int[]{10, 12, 13, 16, 18, 19, 20, 21, 22, 23, - 24, 33, 35, 42, 47}; - - int index = interpolationSearch(x, arr); - - // If element was found - if (index != -1) - System.out.println("Element found at index " + index); - else - System.out.println("Element not found."); - } -} diff --git a/searches/LinearSearch.java b/searches/LinearSearch.java deleted file mode 100644 index 4851194..0000000 --- a/searches/LinearSearch.java +++ /dev/null @@ -1,22 +0,0 @@ -// Java code for linearly search x in arr[]. If x -// is present then return its location, otherwise -// return -1 - -class LinearSearch -{ - // This function returns index of element x in arr[] - static 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 - if (arr[i] == x) - return i; - } - - // return -1 if the element is not found - return -1; - } - -} diff --git a/searches/TernarySearch.java b/searches/TernarySearch.java deleted file mode 100644 index e808e60..0000000 --- a/searches/TernarySearch.java +++ /dev/null @@ -1,20 +0,0 @@ -int ternary_search(int l,int r, int x) -{ - if(r>=l) - { - int mid1 = l + (r-l)/3; - int mid2 = r - (r-l)/3; - if(ar[mid1] == x) - return mid1; - if(ar[mid2] == x) - return mid2; - if(xar[mid2]) - return ternary_search(mid2+1,r,x); - else - return ternary_search(mid1+1,mid2-1,x); - - } - return -1; -} \ No newline at end of file diff --git a/searches/exponential_search.java b/searches/exponential_search.java new file mode 100644 index 0000000..f7571be --- /dev/null +++ b/searches/exponential_search.java @@ -0,0 +1,37 @@ +import java.util.Arrays; + +class Exponential +{ + // Returns position of first occurrence of + // x in array + static int Exponential(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 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 = Exponential(arr, arr.length, x); + + System.out.println((result < 0) ? + "Element is not present in array" : + "Element is present at index " + + result); + } +} 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; + + } + +} 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= 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>{ + 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); + } +} diff --git a/sorting/InsertionSort.java b/sorting/InsertionSort.java index ece1588..b9d6631 100644 --- a/sorting/InsertionSort.java +++ b/sorting/InsertionSort.java @@ -1,52 +1,27 @@ /** - * Java implementation of insertion sort - * - * @author Andres Langberg - */ +* Generic Insertion Sort +* @author Jan Tabacki +*/ - -// Java program for implementation of Insertion Sort -public class InsertionSort -{ - /*Function to sort array using insertion sort*/ - void sort(int arr[]) - { - int n = arr.length; - for (int i=1; i=0 && arr[j] > key) - { - arr[j+1] = arr[j]; - j = j-1; - } - arr[j+1] = key; - } - } - - /* A utility function to print array of size n*/ - static void printArray(int arr[]) - { - int n = arr.length; - for (int i=0; i> { + + /** + * 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]; + 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; + } } 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; + + } + +} 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; + + } + +} diff --git a/sorting/QuickSort.java b/sorting/QuickSort.java index 35ce9d0..6574b38 100644 --- a/sorting/QuickSort.java +++ b/sorting/QuickSort.java @@ -1,98 +1,78 @@ -/** - * Java implementation of quick sort - * - * @author Tibeyev Timur (timurtibeyev@gmail.com) - */ - -public class QuickSort { - - /** - * Method responsible for sorting array. - * - * @param arr array of elements - * @param left start of the segment to sort - * @param right end of the segment to sort - */ - private void sort(int[] arr, int left, int right) { - if (left >= right) { - return; - } - - int i = left; - int j = right; - - int mid = (i + j) / 2; - //Pivot element - int v = arr[mid]; - - while (i < j) { - //Find element from the left side, which is equal or greater than pivot element - while (arr[i] < v) { - i++; - } - - //Find element from the right side, which is equal or less than pivot element - while (v < arr[j]) { - j--; - } - - //If such elements exist, perform swapping - if (i <= j) { - swap(arr, i, j); - i++; - j--; - } - } - - //Recursively sort left subarray - sort(arr, left, j); - //Recursively sort right subarray - sort(arr, i, right); - } - - /** - * Swaps two elements. - * - * @param arr array of elements - * @param i first index - * @param j second index - */ - private void swap(int[] arr, int i, int j) { - int buf = arr[i]; - arr[i] = arr[j]; - arr[j] = buf; - } - - /** - * Entry point, invokes sorting methods and prints resulting array. - * - * @param arr array to sort - */ - public void run(int[] arr) { - sort(arr, 0, arr.length - 1); - printArray(arr); - } - - /** - * Utility method to print array. - * - * @param arr array to print - */ - private void printArray(int[] arr) { - for (int i : arr) { - System.out.print(i+" "); - } - System.out.println(); - } - - /** - * {@code Main} method. - * Initializes {@link QuickSort} object and passes simple array to sort. - * - * @param args cmd arguments - */ - public static void main(String args[]) { - int arr[] = {100, 19, 23, 1, 4 ,23, 66}; - new QuickSort().run(arr); - } -} \ No newline at end of file +// 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; 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 0; h /= 3) - for (int i = l + h; i <= r; i++) { - int j = i, v = a[i]; - while (j >= l + h && v < a[j - h]) { - a[j] = a[j - h]; - j -= h; - } - a[j] = v; - } - } - - public static void main(String[] args) { - int[] a = { 5, 6, 4, 9, 13, 3, 7 }; - ShellSort s = new ShellSort(); - - s.shell(a); - - for (int i = 0; i < a.length; i++) - System.out.println(a[i]); - } - -} \ No newline at end of file +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 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 diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 0000000..e69de29 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