├── MinimizingLateness ├── lateness_data.txt └── MinimizingLateness.java ├── CONTRIBUTING.md ├── DataStructures ├── HashMap │ └── Hashing │ │ ├── Node.java │ │ ├── Main.java │ │ ├── HashMap.java │ │ └── LinkedList.java ├── Heaps │ ├── EmptyHeapException.java │ └── Heap.java ├── Trees │ ├── LevelOrderTraversalQueue.java │ ├── ValidBSTOrNot.java │ ├── LevelOrderTraversal.java │ ├── PrintTopViewofTree.java │ └── TreeTraversal.java ├── Lists │ ├── Merge_K_SortedLinkedlist.java │ ├── MergeSortedArrayList.java │ └── CircleLinkedList.java ├── Stacks │ ├── DecimalToAnyUsingStack.java │ ├── StackArrayList.java │ ├── BalancedBrackets.java │ └── StackOfLinkedList.java ├── Queues │ └── GenericArrayListQueue.java └── Graphs │ ├── Cycles.java │ └── FloydWarshall.java ├── Searches ├── SearchAlgorithm.java ├── JumpSearch.java ├── LinearSearch.java ├── SaddlebackSearch.java ├── InterpolationSearch.java ├── IterativeTernarySearch.java ├── IterativeBinarySearch.java └── BinarySearch.java ├── .gitignore ├── Others ├── FloydTriangle.java ├── Abecedarian.java ├── CountChar.java ├── Krishnamurthy.java ├── EulersFunction.java ├── CRC32.java ├── PowerOfTwoOrNot.java ├── FibToN.java ├── RootPrecision.java ├── TowerOfHanoi.java ├── GuassLegendre.java ├── SieveOfEratosthenes.java ├── ReverseString.java ├── BrianKernighanAlgorithm.java ├── StackPostfixNotation.java ├── RemoveDuplicateFromString.java ├── PasswordGen.java ├── CountWords.java ├── Palindrome.java ├── InsertDeleteInArray.java ├── Armstrong.java ├── ReturnSubsequence.java ├── KMP.java ├── ReverseStackUsingRecursion.java ├── LinearCongruentialGenerator.java ├── Dijkshtra.java └── TopKWords.java ├── Maths ├── AbsoluteValue.java ├── Factorial.java ├── FindMax.java ├── FindMin.java ├── MinValue.java ├── MaxValue.java ├── FactorialRecursion.java ├── Pow.java ├── PowRecursion.java ├── AbsoluteMin.java ├── GCDRecursion.java ├── AbsoluteMax.java ├── PalindromeNumber.java ├── FindMaxRecursion.java ├── FindMinRecursion.java ├── PrimeCheck.java ├── PerfectNumber.java ├── ParseInteger.java ├── FibonacciNumber.java └── GCD.java ├── Conversions ├── DecimalToOctal.java ├── BinaryToDecimal.java ├── AnytoAny.java ├── IntegerToRoman.java ├── HexaDecimalToBinary.java ├── DecimalToHexaDecimal.java ├── HexaDecimalToDecimal.java ├── OctalToDecimal.java ├── BinaryToOctal.java ├── RomanToInteger.java ├── DecimalToBinary.java ├── BinaryToHexadecimal.java ├── OctalToHexadecimal.java ├── AnyBaseToDecimal.java ├── HexToOct.java └── DecimalToAnyBase.java ├── Sorts ├── SortAlgorithm.java ├── PancakeSort.java ├── ShellSort.java ├── GnomeSort.java ├── BubbleSort.java ├── BogoSort.java ├── RadixSort.java ├── InsertionSort.java ├── SelectionSort.java ├── CocktailShakerSort.java ├── SortUtils.java ├── CombSort.java ├── CycleSort.java ├── MergeSort.java ├── QuickSort.java └── CountingSort.java ├── DynamicProgramming ├── RodCutting.java ├── Knapsack.java ├── KadaneAlgorithm.java ├── EggDropping.java ├── LongestValidParentheses.java ├── LevenshteinDistance.java ├── LongestIncreasingSubsequence.java ├── LongestCommonSubsequence.java ├── FordFulkerson.java ├── CoinChange.java ├── Fibonacci.java └── EditDistance.java ├── LICENSE ├── README.md ├── Misc ├── MedianOfRunningArray.java ├── PalindromePrime.java └── heap_sort.java └── ciphers ├── Vigenere.java └── RSA.java /MinimizingLateness/lateness_data.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 3 6 3 | 2 8 4 | 1 9 5 | 4 9 6 | 3 14 7 | 2 15 -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contribution Guidelines 2 | Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 3 | -------------------------------------------------------------------------------- /DataStructures/HashMap/Hashing/Node.java: -------------------------------------------------------------------------------- 1 | package DataStructures.HashMap.Hashing; 2 | 3 | class Node { 4 | int data; 5 | Node next; 6 | 7 | public Node(int data) { 8 | this.data = data; 9 | this.next = null; 10 | } 11 | } -------------------------------------------------------------------------------- /DataStructures/Heaps/EmptyHeapException.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Heaps; 2 | 3 | /** 4 | * @author Nicolas Renard 5 | * Exception to be thrown if the getElement method is used on an empty heap. 6 | */ 7 | @SuppressWarnings("serial") 8 | public class EmptyHeapException extends Exception { 9 | 10 | public EmptyHeapException(String message) { 11 | super(message); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Searches/SearchAlgorithm.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | /** 4 | * The common interface of most searching algorithms 5 | * 6 | * @author Podshivalov Nikita (https://github.com/nikitap492) 7 | **/ 8 | public interface SearchAlgorithm { 9 | 10 | /** 11 | * @param key is an element which should be found 12 | * @param array is an array where the element should be found 13 | * @param Comparable type 14 | * @return first found index of the element 15 | */ 16 | > int find(T array[], T key); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /gradle/wrapper/gradle-wrapper.properties 2 | ##----------Android---------- 3 | # build 4 | *.apk 5 | *.ap_ 6 | *.dex 7 | *.class 8 | bin/ 9 | gen/ 10 | build/ 11 | out/ 12 | 13 | # gradle 14 | .gradle/ 15 | gradle-app.setting 16 | !gradle-wrapper.jar 17 | build/ 18 | 19 | local.properties 20 | 21 | ##----------idea---------- 22 | *.iml 23 | .idea/ 24 | *.ipr 25 | *.iws 26 | 27 | # Android Studio Navigation editor temp files 28 | .navigation/ 29 | 30 | ##----------Other---------- 31 | # osx 32 | *~ 33 | .DS_Store 34 | gradle.properties 35 | 36 | .vscode 37 | 38 | *.log -------------------------------------------------------------------------------- /Others/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | 6 | class FloydTriangle { 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); 10 | int r = sc.nextInt(), n = 0; 11 | sc.close(); 12 | for (int i = 0; i < r; i++) { 13 | for (int j = 0; j <= i; j++) { 14 | System.out.print(++n + " "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Maths/AbsoluteValue.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | /** 4 | * @author PatOnTheBack 5 | */ 6 | 7 | public class AbsoluteValue { 8 | 9 | public static void main(String[] args) { 10 | int value = -34; 11 | System.out.println("The absolute value of " + value + " is " + absVal(value)); 12 | } 13 | 14 | /** 15 | * If value is less than zero, make value positive. 16 | * 17 | * @param value a number 18 | * @return the absolute value of a number 19 | */ 20 | public static int absVal(int value) { 21 | return value < 0 ? -value : value; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Others/Abecedarian.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | /** 4 | * An Abecadrian is a word where each letter is in alphabetical order 5 | * 6 | * @author Oskar Enmalm 7 | */ 8 | class Abecedarian { 9 | 10 | public static boolean isAbecedarian(String s) { 11 | int index = s.length() - 1; 12 | 13 | for (int i = 0; i < index; i++) { 14 | 15 | if (s.charAt(i) <= s.charAt(i + 1)) { 16 | } //Need to check if each letter for the whole word is less than the one before it 17 | 18 | else { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Maths/Factorial.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class Factorial { 4 | public static void main(String[] args) { 5 | int n = 5; 6 | System.out.println(n + "! = " + factorial(n)); 7 | } 8 | 9 | /** 10 | * Calculate factorial 11 | * 12 | * @param n the number 13 | * @return the factorial of {@code n} 14 | */ 15 | public static long factorial(int n) { 16 | if (n < 0) { 17 | throw new ArithmeticException("n < 0"); 18 | } 19 | long fac = 1; 20 | for (int i = 1; i <= n; ++i) { 21 | fac *= i; 22 | } 23 | return fac; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Maths/FindMax.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class FindMax { 4 | 5 | //Driver 6 | public static void main(String[] args) { 7 | int[] array = {2, 4, 9, 7, 19, 94, 5}; 8 | System.out.println("max = " + findMax(array)); 9 | } 10 | 11 | /** 12 | * find max of array 13 | * 14 | * @param array the array contains element 15 | * @return max value 16 | */ 17 | public static int findMax(int[] array) { 18 | int max = array[0]; 19 | for (int i = 1; i < array.length; ++i) { 20 | if (array[i] > max) { 21 | max = array[i]; 22 | } 23 | } 24 | return max; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Maths/FindMin.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class FindMin { 4 | 5 | //Driver 6 | public static void main(String[] args) { 7 | int[] array = {2, 4, 9, 7, 19, 94, 5}; 8 | System.out.println("min = " + findMin(array)); 9 | } 10 | 11 | /** 12 | * Find the minimum number of an array of numbers. 13 | * 14 | * @param array the array contains element 15 | * @return min value 16 | */ 17 | public static int findMin(int[] array) { 18 | int min = array[0]; 19 | for (int i = 1; i < array.length; ++i) { 20 | if (array[i] < min) { 21 | min = array[i]; 22 | } 23 | } 24 | return min; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Maths/MinValue.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class MinValue { 4 | 5 | /** 6 | * Returns the smaller of two {@code int} values. That is, 7 | * the result the argument closer to the value of 8 | * {@link Integer#MIN_VALUE}. If the arguments have the same 9 | * value, the result is that same value. 10 | * 11 | * @param a an argument. 12 | * @param b another argument. 13 | * @return the smaller of {@code a} and {@code b}. 14 | */ 15 | public static int min(int a, int b) { 16 | return a <= b ? a : b; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int a = 3; 21 | int b = 4; 22 | System.out.format("min:%d between %d and %d", min(a, b), a, b); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Others/CountChar.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CountChar { 6 | 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Enter your text: "); 10 | String str = input.nextLine(); 11 | input.close(); 12 | System.out.println("There are " + CountCharacters(str) + " characters."); 13 | } 14 | 15 | /** 16 | * Count non space character in string 17 | * 18 | * @param str String to count the characters 19 | * @return number of character in the specified string 20 | */ 21 | private static int CountCharacters(String str) { 22 | return str.replaceAll("\\s", "").length(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Maths/MaxValue.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class MaxValue { 4 | 5 | /** 6 | * Returns the greater of two {@code int} values. That is, the 7 | * result is the argument closer to the value of 8 | * {@link Integer#MAX_VALUE}. If the arguments have the same value, 9 | * the result is that same value. 10 | * 11 | * @param a an argument. 12 | * @param b another argument. 13 | * @return the larger of {@code a} and {@code b}. 14 | */ 15 | public static int max(int a, int b) { 16 | return a >= b ? a : b; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int a = 3; 21 | int b = 4; 22 | System.out.format("max:%d between %d and %d", max(a, b), a, b); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Maths/FactorialRecursion.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class FactorialRecursion { 4 | 5 | /* Driver Code */ 6 | public static void main(String[] args) { 7 | assert factorial(0) == 1; 8 | assert factorial(1) == 1; 9 | assert factorial(2) == 2; 10 | assert factorial(3) == 6; 11 | assert factorial(5) == 120; 12 | } 13 | 14 | /** 15 | * Recursive FactorialRecursion Method 16 | * 17 | * @param n The number to factorial 18 | * @return The factorial of the number 19 | */ 20 | public static long factorial(int n) { 21 | if (n < 0) { 22 | throw new IllegalArgumentException("number is negative"); 23 | } 24 | return n == 0 || n == 1 ? 1 : n * factorial(n - 1); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Maths/Pow.java: -------------------------------------------------------------------------------- 1 | package maths; 2 | 3 | public class Pow { 4 | public static void main(String[] args) { 5 | assert pow(2, 0) == Math.pow(2, 0); 6 | assert pow(0, 2) == Math.pow(0, 2); 7 | assert pow(2, 10) == Math.pow(2, 10); 8 | assert pow(10, 2) == Math.pow(10, 2); 9 | } 10 | 11 | /** 12 | * Returns the value of the first argument raised to the power of the 13 | * second argument 14 | * 15 | * @param a the base. 16 | * @param b the exponent. 17 | * @return the value {@code a}{@code b}. 18 | */ 19 | public static long pow(int a, int b) { 20 | long result = 1; 21 | for (int i = 1; i <= b; i++) { 22 | result *= a; 23 | } 24 | return result; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Maths/PowRecursion.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class PowRecursion { 4 | public static void main(String[] args) { 5 | assert pow(2, 0) == Math.pow(2, 0); 6 | assert pow(0, 2) == Math.pow(0, 2); 7 | assert pow(2, 10) == Math.pow(2, 10); 8 | assert pow(10, 2) == Math.pow(10, 2); 9 | } 10 | 11 | /** 12 | * Returns the value of the first argument raised to the power of the 13 | * second argument 14 | * 15 | * @param a the base. 16 | * @param b the exponent. 17 | * @return the value {@code a}{@code b}. 18 | */ 19 | public static long pow(int a, int b) { 20 | if (b == 0) { 21 | return 1; 22 | } else { 23 | return a * pow(a, b - 1); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Conversions/DecimalToOctal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts Decimal numbers to Octal Numbers 7 | * 8 | * @author Unknown 9 | */ 10 | public class DecimalToOctal { 11 | /** 12 | * Main Method 13 | * 14 | * @param args Command line Arguments 15 | */ 16 | public static void main(String[] args) { 17 | Scanner sc = new Scanner(System.in); 18 | int n, k, d, s = 0, c = 0; 19 | System.out.print("Decimal number: "); 20 | n = sc.nextInt(); 21 | k = n; 22 | while (k != 0) { 23 | d = k % 8; 24 | s += d * (int) Math.pow(10, c++); 25 | k /= 8; 26 | } 27 | 28 | System.out.println("Octal equivalent:" + s); 29 | sc.close(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Conversions/BinaryToDecimal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Binary number to a Decimal number 7 | * 8 | */ 9 | class BinaryToDecimal { 10 | 11 | /** 12 | * Main Method 13 | * 14 | * @param args Command line arguments 15 | */ 16 | public static void main(String args[]) { 17 | Scanner sc = new Scanner(System.in); 18 | int binNum, binCopy, d, s = 0, power = 0; 19 | System.out.print("Binary number: "); 20 | binNum = sc.nextInt(); 21 | binCopy = binNum; 22 | while (binCopy != 0) { 23 | d = binCopy % 10; 24 | s += d * (int) Math.pow(2, power++); 25 | binCopy /= 10; 26 | } 27 | System.out.println("Decimal equivalent:" + s); 28 | sc.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Others/Krishnamurthy.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | class Krishnamurthy { 6 | static int fact(int n) { 7 | int i, p = 1; 8 | for (i = n; i >= 1; i--) 9 | p = p * i; 10 | return p; 11 | } 12 | 13 | public static void main(String args[]) { 14 | Scanner sc = new Scanner(System.in); 15 | int a, b, s = 0; 16 | System.out.print("Enter the number : "); 17 | a = sc.nextInt(); 18 | int n = a; 19 | while (a > 0) { 20 | b = a % 10; 21 | s = s + fact(b); 22 | a = a / 10; 23 | } 24 | if (s == n) 25 | System.out.print(n + " is a krishnamurthy number"); 26 | else 27 | System.out.print(n + " is not a krishnamurthy number"); 28 | sc.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Others/EulersFunction.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | /** 4 | * You can read more about Euler's totient function 5 | *

6 | * See https://en.wikipedia.org/wiki/Euler%27s_totient_function 7 | */ 8 | public class EulersFunction { 9 | // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time complexity; 10 | public static int getEuler(int n) { 11 | int result = n; 12 | for (int i = 2; i * i <= n; i++) { 13 | if (n % i == 0) { 14 | while (n % i == 0) n /= i; 15 | result -= result / i; 16 | } 17 | } 18 | if (n > 1) result -= result / n; 19 | return result; 20 | } 21 | 22 | public static void main(String[] args) { 23 | for (int i = 1; i < 100; i++) { 24 | System.out.println(getEuler(i)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Conversions/AnytoAny.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | //given a source number , source base, destination base, this code can give you the destination number. 5 | //sn ,sb,db ---> ()dn . this is what we have to do . 6 | 7 | public class AnytoAny { 8 | 9 | public static void main(String[] args) { 10 | Scanner scn = new Scanner(System.in); 11 | int sn = scn.nextInt(); 12 | int sb = scn.nextInt(); 13 | int db = scn.nextInt(); 14 | int m = 1, dec = 0, dn = 0; 15 | while (sn != 0) { 16 | dec = dec + (sn % 10) * m; 17 | m *= sb; 18 | sn /= 10; 19 | } 20 | m = 1; 21 | while (dec != 0) { 22 | dn = dn + (dec % db) * m; 23 | m *= 10; 24 | dec /= db; 25 | } 26 | System.out.println(dn); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Sorts/SortAlgorithm.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * The common interface of most sorting algorithms 8 | * 9 | * @author Podshivalov Nikita (https://github.com/nikitap492) 10 | **/ 11 | public interface SortAlgorithm { 12 | 13 | /** 14 | * Main method arrays sorting algorithms 15 | * 16 | * @param unsorted - an array should be sorted 17 | * @return a sorted array 18 | */ 19 | > T[] sort(T[] unsorted); 20 | 21 | /** 22 | * Auxiliary method for algorithms what wanted to work with lists from JCF 23 | * 24 | * @param unsorted - a list should be sorted 25 | * @return a sorted list 26 | */ 27 | @SuppressWarnings("unchecked") 28 | default > List sort(List unsorted) { 29 | return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Maths/AbsoluteMin.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * description: 7 | *

8 | * absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2 9 | *

10 | */ 11 | public class AbsoluteMin { 12 | public static void main(String[] args) { 13 | int[] numbers = new int[]{3, -10, -2}; 14 | System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers)); 15 | } 16 | 17 | /** 18 | * get the value, it's absolute value is min 19 | * 20 | * @param numbers contains elements 21 | * @return the absolute min value 22 | */ 23 | public static int absMin(int[] numbers) { 24 | int absMinValue = numbers[0]; 25 | for (int i = 1, length = numbers.length; i < length; ++i) { 26 | if (Math.abs(numbers[i]) < Math.abs(absMinValue)) { 27 | absMinValue = numbers[i]; 28 | } 29 | } 30 | return absMinValue; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Maths/GCDRecursion.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | /** 4 | * @author https://github.com/shellhub/ 5 | */ 6 | public class GCDRecursion { 7 | public static void main(String[] args) { 8 | System.out.println(gcd(20, 15)); /* output: 5 */ 9 | System.out.println(gcd(10, 8)); /* output: 2 */ 10 | System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */ 11 | } 12 | 13 | /** 14 | * get greatest common divisor 15 | * 16 | * @param a the first number 17 | * @param b the second number 18 | * @return gcd 19 | */ 20 | public static int gcd(int a, int b) { 21 | 22 | if (a < 0 || b < 0) { 23 | throw new ArithmeticException(); 24 | } 25 | 26 | if (a == 0 || b == 0) { 27 | return Math.abs(a - b); 28 | } 29 | 30 | if (a % b == 0) { 31 | return b; 32 | } else { 33 | return gcd(b, a % b); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Maths/AbsoluteMax.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * description: 7 | *

8 | * absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10 9 | *

10 | */ 11 | public class AbsoluteMax { 12 | public static void main(String[] args) { 13 | int[] numbers = new int[]{3, -10, -2}; 14 | System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers)); 15 | } 16 | 17 | /** 18 | * get the value, it's absolute value is max 19 | * 20 | * @param numbers contains elements 21 | * @return the absolute max value 22 | */ 23 | public static int absMax(int[] numbers) { 24 | int absMaxValue = numbers[0]; 25 | for (int i = 1, length = numbers.length; i < length; ++i) { 26 | if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) { 27 | absMaxValue = numbers[i]; 28 | } 29 | } 30 | return absMaxValue; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Maths/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class PalindromeNumber { 4 | public static void main(String[] args) { 5 | 6 | assert isPalindrome(12321); 7 | assert !isPalindrome(1234); 8 | assert isPalindrome(1); 9 | } 10 | 11 | /** 12 | * Check if {@code n} is palindrome number or not 13 | * 14 | * @param number the number 15 | * @return {@code true} if {@code n} is palindrome number, otherwise {@code false} 16 | */ 17 | public static boolean isPalindrome(int number) { 18 | if (number < 0) { 19 | throw new IllegalArgumentException(number + ""); 20 | } 21 | int numberCopy = number; 22 | int reverseNumber = 0; 23 | while (numberCopy != 0) { 24 | int remainder = numberCopy % 10; 25 | reverseNumber = reverseNumber * 10 + remainder; 26 | numberCopy /= 10; 27 | } 28 | return number == reverseNumber; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Others/CRC32.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.BitSet; 4 | 5 | /** 6 | * Generates a crc32 checksum for a given string or byte array 7 | */ 8 | public class CRC32 { 9 | 10 | public static void main(String[] args) { 11 | System.out.println(Integer.toHexString(crc32("Hello World"))); 12 | } 13 | 14 | public static int crc32(String str) { 15 | return crc32(str.getBytes()); 16 | } 17 | 18 | public static int crc32(byte[] data) { 19 | BitSet bitSet = BitSet.valueOf(data); 20 | int crc32 = 0xFFFFFFFF; // initial value 21 | for (int i = 0; i < data.length * 8; i++) { 22 | if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) 23 | crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial 24 | else 25 | crc32 = (crc32 << 1); 26 | } 27 | crc32 = Integer.reverse(crc32); // result reflect 28 | return crc32 ^ 0xFFFFFFFF; // final xor value 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Others/PowerOfTwoOrNot.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * A utility to check if a given number is power of two or not. 7 | * For example 8,16 etc. 8 | */ 9 | 10 | public class PowerOfTwoOrNot { 11 | 12 | public static void main(String[] args) { 13 | 14 | Scanner sc = new Scanner(System.in); 15 | System.out.println("Enter the number"); 16 | int num = sc.nextInt(); 17 | boolean isPowerOfTwo = checkIfPowerOfTwoOrNot(num); 18 | if (isPowerOfTwo) { 19 | System.out.println("Number is a power of two"); 20 | } else { 21 | System.out.println("Number is not a power of two"); 22 | } 23 | } 24 | 25 | 26 | /** 27 | * Checks whether given number is power of two or not. 28 | * 29 | * @param number 30 | * @return boolean 31 | */ 32 | public static boolean checkIfPowerOfTwoOrNot(int number) { 33 | return number != 0 && ((number & (number - 1)) == 0); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /DynamicProgramming/RodCutting.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * A DynamicProgramming solution for Rod cutting problem 5 | * Returns the best obtainable price for a rod of 6 | * length n and price[] as prices of different pieces 7 | */ 8 | public class RodCutting { 9 | 10 | private static int cutRod(int[] price, int n) { 11 | int val[] = new int[n + 1]; 12 | val[0] = 0; 13 | 14 | for (int i = 1; i <= n; i++) { 15 | int max_val = Integer.MIN_VALUE; 16 | for (int j = 0; j < i; j++) 17 | max_val = Math.max(max_val, price[j] + val[i - j - 1]); 18 | 19 | val[i] = max_val; 20 | } 21 | 22 | return val[n]; 23 | } 24 | 25 | // main function to test 26 | public static void main(String args[]) { 27 | int[] arr = new int[]{2, 5, 13, 19, 20}; 28 | int size = arr.length; 29 | int result = cutRod(arr,size); 30 | System.out.println("Maximum Obtainable Value is " + 31 | result); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Others/FibToN.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Fibonacci sequence, and characterized by the fact that every number 7 | * after the first two is the sum of the two preceding ones. 8 | *

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

11 | * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number 12 | */ 13 | 14 | public class FibToN { 15 | public static void main(String[] args) { 16 | //take input 17 | Scanner scn = new Scanner(System.in); 18 | int N = scn.nextInt(); 19 | // print all Fibonacci numbers that are smaller than your given input N 20 | int first = 0, second = 1; 21 | scn.close(); 22 | while (first <= N) { 23 | //print first fibo 0 then add second fibo into it while updating second as well 24 | 25 | System.out.println(first); 26 | 27 | int next = first + second; 28 | first = second; 29 | second = next; 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Conversions/IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | public class IntegerToRoman { 4 | private static int[] allArabianRomanNumbers = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 5 | private static String[] allRomanNumbers = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 6 | 7 | public static String integerToRoman(int num) { 8 | if (num <= 0) { 9 | return ""; 10 | } 11 | 12 | StringBuilder builder = new StringBuilder(); 13 | 14 | for (int a = 0; a < allArabianRomanNumbers.length; a++) { 15 | int times = num / allArabianRomanNumbers[a]; 16 | for (int b = 0; b < times; b++) { 17 | builder.append(allRomanNumbers[a]); 18 | } 19 | 20 | num -= times * allArabianRomanNumbers[a]; 21 | } 22 | 23 | return builder.toString(); 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(IntegerToRoman.integerToRoman(2131)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Maths/FindMaxRecursion.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class FindMaxRecursion { 4 | public static void main(String[] args) { 5 | int[] array = {2, 4, 9, 7, 19, 94, 5}; 6 | int low = 0; 7 | int high = array.length - 1; 8 | 9 | System.out.println("max value is " + max(array, low, high)); 10 | } 11 | 12 | /** 13 | * Get max of array using divide and conquer algorithm 14 | * 15 | * @param array contains elements 16 | * @param low the index of the first element 17 | * @param high the index of the last element 18 | * @return max of {@code array} 19 | */ 20 | public static int max(int[] array, int low, int high) { 21 | if (low == high) { 22 | return array[low]; //or array[high] 23 | } 24 | 25 | int mid = (low + high) >>> 1; 26 | 27 | int leftMax = max(array, low, mid); //get max in [low, mid] 28 | int rightMax = max(array, mid + 1, high); //get max in [mid+1, high] 29 | 30 | return leftMax >= rightMax ? leftMax : rightMax; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Maths/FindMinRecursion.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class FindMinRecursion { 4 | public static void main(String[] args) { 5 | int[] array = {2, 4, 9, 7, 19, 94, 5}; 6 | int low = 0; 7 | int high = array.length - 1; 8 | 9 | System.out.println("min value is " + min(array, low, high)); 10 | } 11 | 12 | /** 13 | * Get min of array using divide and conquer algorithm 14 | * 15 | * @param array contains elements 16 | * @param low the index of the first element 17 | * @param high the index of the last element 18 | * @return min of {@code array} 19 | */ 20 | public static int min(int[] array, int low, int high) { 21 | if (low == high) { 22 | return array[low]; //or array[high] 23 | } 24 | 25 | int mid = (low + high) >>> 1; 26 | 27 | int leftMin = min(array, low, mid); //get min in [low, mid] 28 | int rightMin = min(array, mid + 1, high); //get min in [mid+1, high] 29 | 30 | return leftMin <= rightMin ? leftMin : rightMin; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Others/RootPrecision.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class RootPrecision { 6 | 7 | public static void main(String[] args) { 8 | // take input 9 | Scanner scn = new Scanner(System.in); 10 | 11 | // N is the input number 12 | int N = scn.nextInt(); 13 | 14 | // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. 15 | int P = scn.nextInt(); 16 | System.out.println(squareRoot(N, P)); 17 | } 18 | 19 | public static double squareRoot(int N, int P) { 20 | // rv means return value 21 | double rv; 22 | 23 | double root = Math.pow(N, 0.5); 24 | 25 | // calculate precision to power of 10 and then multiply it with root value. 26 | int precision = (int) Math.pow(10, P); 27 | root = root * precision; 28 | /*typecast it into integer then divide by precision and again typecast into double 29 | so as to have decimal points upto P precision */ 30 | 31 | rv = (int) root; 32 | return rv / precision; 33 | } 34 | } -------------------------------------------------------------------------------- /Maths/PrimeCheck.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PrimeCheck { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | System.out.print("Enter a number: "); 10 | int n = scanner.nextInt(); 11 | if (isPrime(n)) { 12 | System.out.println(n + " is a prime number"); 13 | } else { 14 | System.out.println(n + " is not a prime number"); 15 | } 16 | } 17 | 18 | /*** 19 | * Checks if a number is prime or not 20 | * @param n the number 21 | * @return {@code true} if {@code n} is prime 22 | */ 23 | public static boolean isPrime(int n) { 24 | if (n == 2) { 25 | return true; 26 | } 27 | if (n < 2 || n % 2 == 0) { 28 | return false; 29 | } 30 | for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { 31 | if (n % i == 0) { 32 | return false; 33 | } 34 | } 35 | return true; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /DataStructures/HashMap/Hashing/Main.java: -------------------------------------------------------------------------------- 1 | package DataStructures.HashMap.Hashing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | 8 | int choice, key; 9 | 10 | HashMap h = new HashMap(7); 11 | 12 | while (true) { 13 | System.out.println("Enter your Choice :"); 14 | System.out.println("1. Add Key"); 15 | System.out.println("2. Delete Key"); 16 | System.out.println("3. Print Table"); 17 | System.out.println("4. Exit"); 18 | 19 | Scanner In = new Scanner(System.in); 20 | 21 | choice = In.nextInt(); 22 | 23 | switch (choice) { 24 | case 1: { 25 | System.out.println("Enter the Key: "); 26 | key = In.nextInt(); 27 | h.insertHash(key); 28 | break; 29 | } 30 | case 2: { 31 | System.out.println("Enter the Key delete: "); 32 | key = In.nextInt(); 33 | h.deleteHash(key); 34 | break; 35 | } 36 | case 3: { 37 | System.out.println("Print table"); 38 | h.displayHashtable(); 39 | break; 40 | } 41 | case 4: { 42 | return; 43 | } 44 | } 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /Conversions/HexaDecimalToBinary.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | public class HexaDecimalToBinary { 4 | 5 | private final int LONG_BITS = 8; 6 | 7 | public void convert(String numHex) { 8 | // String a HexaDecimal: 9 | int conHex = Integer.parseInt(numHex, 16); 10 | // Hex a Binary: 11 | String binary = Integer.toBinaryString(conHex); 12 | // Presentation: 13 | System.out.println(numHex + " = " + completeDigits(binary)); 14 | } 15 | 16 | public String completeDigits(String binNum) { 17 | for (int i = binNum.length(); i < LONG_BITS; i++) { 18 | binNum = "0" + binNum; 19 | } 20 | return binNum; 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | //Testing Numbers: 26 | String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", 27 | "19", "01", "02", "03", "04"}; 28 | HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); 29 | 30 | for (String num : hexNums) { 31 | objConvert.convert(num); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 The Algorithms 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /DataStructures/HashMap/Hashing/HashMap.java: -------------------------------------------------------------------------------- 1 | package DataStructures.HashMap.Hashing; 2 | 3 | 4 | class HashMap { 5 | private int hsize; 6 | private LinkedList[] buckets; 7 | 8 | public HashMap(int hsize) { 9 | buckets = new LinkedList[hsize]; 10 | for (int i = 0; i < hsize; i++) { 11 | buckets[i] = new LinkedList(); 12 | // Java requires explicit initialisaton of each object 13 | } 14 | this.hsize = hsize; 15 | } 16 | 17 | public int hashing(int key) { 18 | int hash = key % hsize; 19 | if (hash < 0) 20 | hash += hsize; 21 | return hash; 22 | } 23 | 24 | public void insertHash(int key) { 25 | int hash = hashing(key); 26 | buckets[hash].insert(key); 27 | } 28 | 29 | 30 | public void deleteHash(int key) { 31 | int hash = hashing(key); 32 | 33 | buckets[hash].delete(key); 34 | } 35 | 36 | public void displayHashtable() { 37 | for (int i = 0; i < hsize; i++) { 38 | System.out.printf("Bucket %d :", i); 39 | buckets[i].display(); 40 | } 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /Others/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | class TowerOfHanoi { 6 | public static void shift(int n, String startPole, String intermediatePole, String endPole) { 7 | // if n becomes zero the program returns thus ending the loop. 8 | if (n == 0) { 9 | return; 10 | } 11 | 12 | 13 | // Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole 14 | shift(n - 1, startPole, endPole, intermediatePole); 15 | System.out.println("\nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing 16 | // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole 17 | shift(n - 1, intermediatePole, startPole, endPole); 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.print("Enter number of discs on Pole 1: "); 22 | Scanner scanner = new Scanner(System.in); 23 | int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1 24 | shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Maths/PerfectNumber.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | /** 4 | * In number theory, a perfect number is a positive integer that is equal to the sum of 5 | * its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 6 | * (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number. 7 | *

8 | * link:https://en.wikipedia.org/wiki/Perfect_number 9 | *

10 | */ 11 | public class PerfectNumber { 12 | public static void main(String[] args) { 13 | assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */ 14 | assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */ 15 | assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */ 16 | } 17 | 18 | /** 19 | * Check if {@code number} is perfect number or not 20 | * 21 | * @param number the number 22 | * @return {@code true} if {@code number} is perfect number, otherwise false 23 | */ 24 | public static boolean isPerfectNumber(int number) { 25 | int sum = 0; /* sum of its positive divisors */ 26 | for (int i = 1; i < number; ++i) { 27 | if (number % i == 0) { 28 | sum += i; 29 | } 30 | } 31 | return sum == number; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Others/GuassLegendre.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.lang.Math; 4 | 5 | /** 6 | * Guass Legendre Algorithm 7 | * ref https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm 8 | * 9 | * @author AKS1996 10 | */ 11 | public class GuassLegendre { 12 | 13 | public static void main(String[] args) { 14 | for (int i = 1; i <= 3; ++i) 15 | System.out.println(pi(i)); 16 | 17 | } 18 | 19 | static double pi(int l) { 20 | /* 21 | * l: No of loops to run 22 | */ 23 | 24 | double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; 25 | for (int i = 0; i < l; ++i) { 26 | double temp[] = update(a, b, t, p); 27 | a = temp[0]; 28 | b = temp[1]; 29 | t = temp[2]; 30 | p = temp[3]; 31 | } 32 | 33 | return Math.pow(a + b, 2) / (4 * t); 34 | } 35 | 36 | static double[] update(double a, double b, double t, double p) { 37 | double values[] = new double[4]; 38 | values[0] = (a + b) / 2; 39 | values[1] = Math.sqrt(a * b); 40 | values[2] = t - p * Math.pow(a - values[0], 2); 41 | values[3] = 2 * p; 42 | 43 | return values; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Sorts/PancakeSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.*; 4 | 5 | /** 6 | * Implementation of gnome sort 7 | * 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | * @since 2018-04-10 10 | **/ 11 | public class PancakeSort implements SortAlgorithm { 12 | 13 | @Override 14 | public > T[] sort(T[] array) { 15 | int size = array.length; 16 | 17 | for (int i = 0; i < size; i++) { 18 | T max = array[0]; 19 | int index = 0; 20 | for (int j = 0; j < size - i; j++) { 21 | if (less(max, array[j])) { 22 | max = array[j]; 23 | index = j; 24 | } 25 | } 26 | flip(array, index, array.length - 1 - i); 27 | } 28 | return array; 29 | } 30 | 31 | 32 | public static void main(String[] args) { 33 | 34 | Integer[] arr = {10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1}; 35 | PancakeSort pancakeSort = new PancakeSort(); 36 | System.out.println("After sorting:"); 37 | pancakeSort.sort(arr); 38 | print(arr); 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /DataStructures/HashMap/Hashing/LinkedList.java: -------------------------------------------------------------------------------- 1 | package DataStructures.HashMap.Hashing; 2 | 3 | class LinkedList { 4 | 5 | private Node Head; 6 | private int size; 7 | 8 | public LinkedList() { 9 | Head = null; 10 | size = 0; 11 | } 12 | 13 | public void insert(int data) { 14 | 15 | Node temp = Head; 16 | Node newnode = new Node(data); 17 | 18 | size++; 19 | 20 | if(Head == null) { 21 | Head = newnode; 22 | } 23 | else { 24 | newnode.next = Head; 25 | Head = newnode; 26 | } 27 | } 28 | 29 | public void delete(int data) { 30 | if(size == 0) { 31 | System.out.println("UnderFlow!"); 32 | return; 33 | } 34 | 35 | else { 36 | Node curr = Head; 37 | if (curr.data == data) { 38 | Head = curr.next; 39 | size--; 40 | return; 41 | } 42 | else { 43 | 44 | while(curr.next.next != null) { 45 | if(curr.next.data == data){ 46 | curr.next = curr.next.next; 47 | return; 48 | } 49 | } 50 | 51 | System.out.println("Key not Found"); 52 | } 53 | } 54 | } 55 | 56 | public void display() { 57 | Node temp = Head; 58 | while(temp != null) { 59 | System.out.printf("%d ",temp.data); 60 | temp = temp.next; 61 | } 62 | System.out.println(); 63 | } 64 | } -------------------------------------------------------------------------------- /Conversions/DecimalToHexaDecimal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | class DecimalToHexaDecimal { 4 | private static final int sizeOfIntInHalfBytes = 8; 5 | private static final int numberOfBitsInAHalfByte = 4; 6 | private static final int halfByte = 0x0F; 7 | private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 8 | 'F' }; 9 | 10 | // Returns the hex value of the dec entered in the parameter. 11 | public static String decToHex(int dec) { 12 | StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); 13 | hexBuilder.setLength(sizeOfIntInHalfBytes); 14 | for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) { 15 | int j = dec & halfByte; 16 | hexBuilder.setCharAt(i, hexDigits[j]); 17 | dec >>= numberOfBitsInAHalfByte; 18 | } 19 | return hexBuilder.toString().toLowerCase(); 20 | } 21 | 22 | // Test above function. 23 | public static void main(String[] args) { 24 | System.out.println("Test..."); 25 | int dec = 305445566; 26 | String libraryDecToHex = Integer.toHexString(dec); 27 | String decToHex = decToHex(dec); 28 | System.out.println("Result from the library : " + libraryDecToHex); 29 | System.out.println("Result decToHex method : " + decToHex); 30 | } 31 | } -------------------------------------------------------------------------------- /Sorts/ShellSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.*; 4 | 5 | 6 | /** 7 | * @author dpunosevac 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | * @see SortAlgorithm 10 | */ 11 | public class ShellSort implements SortAlgorithm { 12 | 13 | /** 14 | * This method implements Generic Shell Sort. 15 | * 16 | * @param array The array to be sorted 17 | */ 18 | @Override 19 | public > T[] sort(T[] array) { 20 | int N = array.length; 21 | int h = 1; 22 | 23 | while (h < N / 3) { 24 | h = 3 * h + 1; 25 | } 26 | 27 | while (h >= 1) { 28 | for (int i = h; i < N; i++) { 29 | for (int j = i; j >= h && less(array[j], array[j - h]); j -= h) { 30 | swap(array, j, j - h); 31 | } 32 | } 33 | 34 | h /= 3; 35 | } 36 | 37 | return array; 38 | } 39 | 40 | public static void main(String[] args) { 41 | Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 42 | 43 | ShellSort sort = new ShellSort(); 44 | Integer[] sorted = sort.sort(toSort); 45 | 46 | print(sorted); 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Sorts/GnomeSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.*; 4 | 5 | /** 6 | * Implementation of gnome sort 7 | * 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | * @since 2018-04-10 10 | **/ 11 | public class GnomeSort implements SortAlgorithm { 12 | 13 | @Override 14 | public > T[] sort(T[] arr) { 15 | int i = 1; 16 | int j = 2; 17 | while (i < arr.length) { 18 | if (less(arr[i - 1], arr[i])) i = j++; 19 | else { 20 | swap(arr, i - 1, i); 21 | if (--i == 0) { 22 | i = j++; 23 | } 24 | } 25 | } 26 | 27 | return null; 28 | } 29 | 30 | public static void main(String[] args) { 31 | Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; 32 | String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"}; 33 | GnomeSort gnomeSort = new GnomeSort(); 34 | 35 | gnomeSort.sort(integers); 36 | gnomeSort.sort(strings); 37 | 38 | System.out.println("After sort : "); 39 | print(integers); 40 | print(strings); 41 | 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Conversions/HexaDecimalToDecimal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class HexaDecimalToDecimal { 6 | 7 | // convert hexadecimal to decimal 8 | public static int getHexaToDec(String hex) { 9 | String digits = "0123456789ABCDEF"; 10 | hex = hex.toUpperCase(); 11 | int val = 0; 12 | for (int i = 0; i < hex.length(); i++) { 13 | int d = digits.indexOf(hex.charAt(i)); 14 | val = 16 * val + d; 15 | } 16 | return val; 17 | } 18 | 19 | // Main method gets the hexadecimal input from user and converts it into Decimal output. 20 | 21 | public static void main(String args[]) { 22 | String hexa_Input; 23 | int dec_output; 24 | Scanner scan = new Scanner(System.in); 25 | 26 | System.out.print("Enter Hexadecimal Number : "); 27 | hexa_Input = scan.nextLine(); 28 | 29 | // convert hexadecimal to decimal 30 | 31 | dec_output = getHexaToDec(hexa_Input); 32 | /* 33 | Pass the string to the getHexaToDec function 34 | and it returns the decimal form in the variable dec_output. 35 | */ 36 | System.out.println("Number in Decimal: " + dec_output); 37 | 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Maths/ParseInteger.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | public class ParseInteger { 4 | public static void main(String[] args) { 5 | assert parseInt("123") == Integer.parseInt("123"); 6 | assert parseInt("-123") == Integer.parseInt("-123"); 7 | assert parseInt("0123") == Integer.parseInt("0123"); 8 | assert parseInt("+123") == Integer.parseInt("+123"); 9 | } 10 | 11 | /** 12 | * Parse a string to integer 13 | * 14 | * @param s the string 15 | * @return the integer value represented by the argument in decimal. 16 | * @throws NumberFormatException if the {@code string} does not contain a parsable integer. 17 | */ 18 | public static int parseInt(String s) { 19 | if (s == null) { 20 | throw new NumberFormatException("null"); 21 | } 22 | boolean isNegative = s.charAt(0) == '-'; 23 | boolean isPositive = s.charAt(0) == '+'; 24 | int number = 0; 25 | for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) { 26 | if (!Character.isDigit(s.charAt(i))) { 27 | throw new NumberFormatException("s=" + s); 28 | } 29 | number = number * 10 + s.charAt(i) - '0'; 30 | } 31 | return isNegative ? -number : number; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DynamicProgramming/Knapsack.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * A DynamicProgramming based solution for 0-1 Knapsack problem 5 | */ 6 | 7 | public class Knapsack { 8 | 9 | private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { 10 | if(wt == null || val == null) 11 | throw new IllegalArgumentException(); 12 | int i, w; 13 | int rv[][] = new int[n + 1][W + 1]; //rv means return value 14 | 15 | // Build table rv[][] in bottom up manner 16 | for (i = 0; i <= n; i++) { 17 | for (w = 0; w <= W; w++) { 18 | if (i == 0 || w == 0) 19 | rv[i][w] = 0; 20 | else if (wt[i - 1] <= w) 21 | rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); 22 | else 23 | rv[i][w] = rv[i - 1][w]; 24 | } 25 | } 26 | 27 | return rv[n][W]; 28 | } 29 | 30 | 31 | // Driver program to test above function 32 | public static void main(String args[]) { 33 | int val[] = new int[]{50, 100, 130}; 34 | int wt[] = new int[]{10, 20, 40}; 35 | int W = 50; 36 | int n = val.length; 37 | System.out.println(knapSack(W, wt, val, n)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Algorithms - Java 2 | [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100) 3 | 4 | 5 | NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we are trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info. 6 | 7 | You can play around (run and edit) the Algorithms or contribute to them using Gitpod.io a free online dev environment with a single click. No need to worry about the Dev enviroment. 8 | 9 | [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) 10 | 11 | 12 | ### All algorithms implemented in Java (for education) 13 | These implementations are for learning purposes. They may be less efficient than the implementations in the Java standard library. 14 | 15 | ## Contribution Guidelines 16 | Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 17 | 18 | ## Community Channel 19 | We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us. 20 | 21 | ## Algorithms 22 | See our [directory](DIRECTORY.md). 23 | -------------------------------------------------------------------------------- /Others/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | */ 6 | public class SieveOfEratosthenes { 7 | 8 | /** 9 | * This method implements the Sieve of Eratosthenes Algorithm 10 | * 11 | * @param n The number till which we have to check for prime 12 | * Prints all the prime numbers till n 13 | **/ 14 | 15 | public static void findPrimesTillN(int n) { 16 | int[] arr = new int[n + 1]; 17 | 18 | for (int i = 0; i <= n; i++) { 19 | arr[i] = 1; 20 | } 21 | 22 | arr[0] = arr[1] = 0; 23 | 24 | for (int i = 2; i <= Math.sqrt(n); i++) { 25 | if (arr[i] == 1) { 26 | for (int j = 2; i * j <= n; j++) { 27 | arr[i * j] = 0; 28 | } 29 | } 30 | } 31 | 32 | for (int i = 0; i < n + 1; i++) { 33 | if (arr[i] == 1) { 34 | System.out.print(i + " "); 35 | } 36 | } 37 | 38 | System.out.println(); 39 | } 40 | 41 | // Driver Program 42 | public static void main(String[] args) { 43 | int n = 100; 44 | 45 | // Prints 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 46 | findPrimesTillN(n); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Conversions/OctalToDecimal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Octal Number to a Decimal Number 7 | * 8 | * @author Zachary Jones 9 | * 10 | */ 11 | public class OctalToDecimal { 12 | 13 | /** 14 | * Main method 15 | * 16 | * @param args 17 | * Command line arguments 18 | */ 19 | public static void main(String args[]) { 20 | Scanner sc = new Scanner(System.in); 21 | System.out.print("Octal Input: "); 22 | String inputOctal = sc.nextLine(); 23 | int result = convertOctalToDecimal(inputOctal); 24 | if (result != -1) 25 | System.out.println("Result convertOctalToDecimal : " + result); 26 | sc.close(); 27 | } 28 | 29 | /** 30 | * This method converts an octal number to a decimal number. 31 | * 32 | * @param inputOctal 33 | * The octal number 34 | * @return The decimal number 35 | */ 36 | public static int convertOctalToDecimal(String inputOctal) { 37 | 38 | try { 39 | // Actual conversion of Octal to Decimal: 40 | Integer outputDecimal = Integer.parseInt(inputOctal, 8); 41 | return outputDecimal; 42 | } catch (NumberFormatException ne) { 43 | // Printing a warning message if the input is not a valid octal 44 | // number: 45 | System.out.println("Invalid Input, Expecting octal number 0-7"); 46 | return -1; 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /Maths/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | /** 4 | * Fibonacci: 0 1 1 2 3 5 8 13 21 ... 5 | */ 6 | public class FibonacciNumber { 7 | public static void main(String[] args) { 8 | assert isFibonacciNumber(1); 9 | assert isFibonacciNumber(2); 10 | assert isFibonacciNumber(21); 11 | assert !isFibonacciNumber(9); 12 | assert !isFibonacciNumber(10); 13 | } 14 | 15 | /** 16 | * Check if a number is perfect square number 17 | * 18 | * @param number the number to be checked 19 | * @return true if {@code number} is perfect square, otherwise false 20 | */ 21 | public static boolean isPerfectSquare(int number) { 22 | int sqrt = (int) Math.sqrt(number); 23 | return sqrt * sqrt == number; 24 | } 25 | 26 | /** 27 | * Check if a number is fibonacci number 28 | * This is true if and only if at least one of 5x^2+4 or 5x^2-4 is a perfect square 29 | * 30 | * @param number the number 31 | * @return true if {@code number} is fibonacci number, otherwise false 32 | * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification 33 | */ 34 | public static boolean isFibonacciNumber(int number) { 35 | return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Conversions/BinaryToOctal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Binary number to an Octal Number 7 | * 8 | * @author Zachary Jones 9 | */ 10 | public class BinaryToOctal { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.println("Input the binary number: "); 20 | int b = sc.nextInt(); 21 | System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); 22 | sc.close(); 23 | 24 | } 25 | 26 | /** 27 | * This method converts a binary number to 28 | * an octal number. 29 | * 30 | * @param binary The binary number 31 | * @return The octal number 32 | */ 33 | public static String convertBinaryToOctal(int binary) { 34 | String octal = ""; 35 | int currBit = 0, j = 1; 36 | while (binary != 0) { 37 | int code3 = 0; 38 | for (int i = 0; i < 3; i++) { 39 | currBit = binary % 10; 40 | binary = binary / 10; 41 | code3 += currBit * j; 42 | j *= 2; 43 | } 44 | octal = code3 + octal; 45 | j = 1; 46 | } 47 | return octal; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Others/ReverseString.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | /** 8 | * This method produces a reversed version of a string 9 | * 10 | * @author Unknown 11 | */ 12 | public class ReverseString { 13 | 14 | /** 15 | * This method reverses the string str and returns it 16 | * 17 | * @param str String to be reversed 18 | * @return Reversed string 19 | */ 20 | public static String reverse(String str) { 21 | if (str == null || str.isEmpty()) return str; 22 | 23 | char[] arr = str.toCharArray(); 24 | for (int i = 0, j = str.length() - 1; i < j; i++, j--) { 25 | char temp = arr[i]; 26 | arr[i] = arr[j]; 27 | arr[j] = temp; 28 | } 29 | return new String(arr); 30 | } 31 | 32 | /** 33 | * Main Method 34 | * 35 | * @param args Command line arguments 36 | * @throws IOException Exception thrown because of BufferedReader 37 | */ 38 | public static void main(String[] args) throws IOException { 39 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 40 | System.out.println("Enter the string"); 41 | String srr = br.readLine(); 42 | System.out.println("Reverse=" + reverse(srr)); 43 | br.close(); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /DataStructures/Trees/LevelOrderTraversalQueue.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Trees; 2 | 3 | import java.util.Queue; 4 | import java.util.LinkedList; 5 | 6 | 7 | /* Class to print Level Order Traversal */ 8 | public class LevelOrderTraversalQueue { 9 | 10 | /* Class to represent Tree node */ 11 | class Node { 12 | int data; 13 | Node left, right; 14 | 15 | public Node(int item) { 16 | data = item; 17 | left = null; 18 | right = null; 19 | } 20 | } 21 | 22 | Node root; 23 | 24 | /* Given a binary tree. Print its nodes in level order 25 | using array for implementing queue */ 26 | void printLevelOrder() { 27 | Queue queue = new LinkedList(); 28 | queue.add(root); 29 | while (!queue.isEmpty()) { 30 | 31 | /* poll() removes the present head. 32 | For more information on poll() visit 33 | http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */ 34 | Node tempNode = queue.poll(); 35 | System.out.print(tempNode.data + " "); 36 | 37 | /*Enqueue left child */ 38 | if (tempNode.left != null) { 39 | queue.add(tempNode.left); 40 | } 41 | 42 | /*Enqueue right child */ 43 | if (tempNode.right != null) { 44 | queue.add(tempNode.right); 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Searches/JumpSearch.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | public class JumpSearch implements SearchAlgorithm { 4 | 5 | public static void main(String[] args) { 6 | JumpSearch jumpSearch = new JumpSearch(); 7 | Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 8 | for (int i = 0; i < array.length; i++) { 9 | assert jumpSearch.find(array, i) == i; 10 | } 11 | assert jumpSearch.find(array, -1) == -1; 12 | assert jumpSearch.find(array, 11) == -1; 13 | } 14 | 15 | /** 16 | * Jump Search algorithm implements 17 | * 18 | * @param array the array contains elements 19 | * @param key to be searched 20 | * @return index of {@code key} if found, otherwise -1 21 | */ 22 | @Override 23 | public > int find(T[] array, T key) { 24 | int length = array.length; /* length of array */ 25 | int blockSize = (int) Math.sqrt(length); /* block size to be jumped */ 26 | 27 | int limit = blockSize; 28 | while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) { 29 | limit = Math.min(limit + blockSize, array.length - 1); 30 | } 31 | 32 | for (int i = limit - blockSize; i <= limit; i++) { 33 | if (array[i] == key) { /* execute linear search */ 34 | return i; 35 | } 36 | } 37 | return -1; /* not found */ 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /DataStructures/Trees/ValidBSTOrNot.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Trees; 2 | 3 | public class ValidBSTOrNot { 4 | 5 | class Node { 6 | int data; 7 | Node left, right; 8 | 9 | public Node(int item) { 10 | data = item; 11 | left = right = null; 12 | } 13 | } 14 | 15 | //Root of the Binary Tree 16 | Node root; 17 | 18 | /* can give min and max value according to your code or 19 | can write a function to find min and max value of tree. */ 20 | 21 | /* returns true if given search tree is binary 22 | search tree (efficient version) */ 23 | boolean isBST() { 24 | return isBSTUtil(root, Integer.MIN_VALUE, 25 | Integer.MAX_VALUE); 26 | } 27 | 28 | /* Returns true if the given tree is a BST and its 29 | values are >= min and <= max. */ 30 | boolean isBSTUtil(Node node, int min, int max) { 31 | /* an empty tree is BST */ 32 | if (node == null) 33 | return true; 34 | 35 | /* false if this node violates the min/max constraints */ 36 | if (node.data < min || node.data > max) 37 | return false; 38 | 39 | /* otherwise check the subtrees recursively 40 | tightening the min/max constraints */ 41 | // Allow only distinct values 42 | return (isBSTUtil(node.left, min, node.data - 1) && 43 | isBSTUtil(node.right, node.data + 1, max)); 44 | } 45 | } -------------------------------------------------------------------------------- /Others/BrianKernighanAlgorithm.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @author Nishita Aggarwal 7 | *

8 | * Brian Kernighan’s Algorithm 9 | *

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

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

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

18 | *

19 | * Time Complexity: O(logn) 20 | */ 21 | 22 | 23 | public class BrianKernighanAlgorithm { 24 | 25 | /** 26 | * @param num: number in which we count the set bits 27 | * @return int: Number of set bits 28 | */ 29 | static int countSetBits(int num) { 30 | int cnt = 0; 31 | while (num != 0) { 32 | num = num & (num - 1); 33 | cnt++; 34 | } 35 | return cnt; 36 | } 37 | 38 | 39 | /** 40 | * @param args : command line arguments 41 | */ 42 | public static void main(String args[]) { 43 | Scanner sc = new Scanner(System.in); 44 | int num = sc.nextInt(); 45 | int setBitCount = countSetBits(num); 46 | System.out.println(setBitCount); 47 | sc.close(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Misc/MedianOfRunningArray.java: -------------------------------------------------------------------------------- 1 | package Misc; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | 6 | 7 | /** 8 | * @author shrutisheoran 9 | */ 10 | public class MedianOfRunningArray { 11 | private PriorityQueue p1; 12 | private PriorityQueue p2; 13 | 14 | //Constructor 15 | public MedianOfRunningArray() { 16 | this.p1 = new PriorityQueue<>(Collections.reverseOrder()); //Max Heap 17 | this.p2 = new PriorityQueue<>(); //Min Heap 18 | } 19 | 20 | /* 21 | Inserting lower half of array to max Heap 22 | and upper half to min heap 23 | */ 24 | public void insert(Integer e) { 25 | p2.add(e); 26 | if (p2.size() - p1.size() > 1) 27 | p1.add(p2.remove()); 28 | } 29 | 30 | /* 31 | Returns median at any given point 32 | */ 33 | public Integer median() { 34 | if (p1.size() == p2.size()) 35 | return (p1.peek() + p2.peek()) / 2; 36 | return p1.size() > p2.size() ? p1.peek() : p2.peek(); 37 | } 38 | 39 | public static void main(String[] args) { 40 | /* 41 | Testing the median function 42 | */ 43 | 44 | MedianOfRunningArray p = new MedianOfRunningArray(); 45 | int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; 46 | for (int i = 0; i < 9; i++) { 47 | p.insert(arr[i]); 48 | System.out.print(p.median() + " "); 49 | } 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /Others/StackPostfixNotation.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.*; 4 | 5 | public class StackPostfixNotation { 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +" 9 | System.out.println(postfixEvaluate(post)); 10 | } 11 | 12 | // Evaluates the given postfix expression string and returns the result. 13 | public static int postfixEvaluate(String exp) { 14 | Stack s = new Stack(); 15 | Scanner tokens = new Scanner(exp); 16 | 17 | while (tokens.hasNext()) { 18 | if (tokens.hasNextInt()) { 19 | s.push(tokens.nextInt()); // If int then push to stack 20 | } else { // else pop top two values and perform the operation 21 | int num2 = s.pop(); 22 | int num1 = s.pop(); 23 | String op = tokens.next(); 24 | 25 | if (op.equals("+")) { 26 | s.push(num1 + num2); 27 | } else if (op.equals("-")) { 28 | s.push(num1 - num2); 29 | } else if (op.equals("*")) { 30 | s.push(num1 * num2); 31 | } else { 32 | s.push(num1 / num2); 33 | } 34 | 35 | // "+", "-", "*", "/" 36 | } 37 | } 38 | return s.pop(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Others/RemoveDuplicateFromString.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | 6 | /** 7 | * @author Varun Upadhyay (https://github.com/varunu28) 8 | */ 9 | 10 | public class RemoveDuplicateFromString { 11 | public static void main(String[] args) throws Exception { 12 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 13 | String inpStr = br.readLine(); 14 | 15 | System.out.println("Actual string is: " + inpStr); 16 | System.out.println("String after removing duplicates: " + removeDuplicate(inpStr)); 17 | 18 | br.close(); 19 | } 20 | 21 | /** 22 | * This method produces a string after removing all the duplicate characters from input string and returns it 23 | * Example: Input String - "aabbbccccddddd" 24 | * Output String - "abcd" 25 | * 26 | * @param s String from which duplicate characters have to be removed 27 | * @return string with only unique characters 28 | */ 29 | 30 | public static String removeDuplicate(String s) { 31 | if (s == null || s.isEmpty()) { 32 | return s; 33 | } 34 | 35 | StringBuilder sb = new StringBuilder(); 36 | int n = s.length(); 37 | 38 | for (int i = 0; i < n; i++) { 39 | if (sb.toString().indexOf(s.charAt(i)) == -1) { 40 | sb.append(String.valueOf(s.charAt(i))); 41 | } 42 | } 43 | 44 | return sb.toString(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Others/PasswordGen.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Collections; 4 | import java.util.Random; 5 | import java.util.List; 6 | import java.util.ArrayList; 7 | 8 | 9 | /** 10 | * Creates a random password from ASCII letters 11 | * Given password length bounds 12 | * 13 | * @author AKS1996 14 | * @date 2017.10.25 15 | */ 16 | class PasswordGen { 17 | public static void main(String args[]) { 18 | String password = generatePassword(8, 16); 19 | System.out.print("Password: " + password); 20 | } 21 | 22 | static String generatePassword(int min_length, int max_length) { 23 | Random random = new Random(); 24 | 25 | String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 26 | String lower = "abcdefghijklmnopqrstuvwxyz"; 27 | String numbers = "0123456789"; 28 | String specialChars = "!@#$%^&*(){}?"; 29 | 30 | String allChars = upper + lower + numbers + specialChars; 31 | 32 | List letters = new ArrayList(); 33 | for (char c : allChars.toCharArray()) 34 | letters.add(c); 35 | 36 | // Inbuilt method to randomly shuffle a elements of a list 37 | Collections.shuffle(letters); 38 | String password = ""; 39 | 40 | // Note that size of the password is also random 41 | for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { 42 | password += letters.get(random.nextInt(letters.size())); 43 | } 44 | 45 | return password; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Sorts/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.*; 4 | 5 | /** 6 | * @author Varun Upadhyay (https://github.com/varunu28) 7 | * @author Podshivalov Nikita (https://github.com/nikitap492) 8 | * @see SortAlgorithm 9 | */ 10 | 11 | class BubbleSort implements SortAlgorithm { 12 | /** 13 | * This method implements the Generic Bubble Sort 14 | * 15 | * @param array The array to be sorted 16 | * Sorts the array in increasing order 17 | **/ 18 | 19 | @Override 20 | public > T[] sort(T array[]) { 21 | for (int i = 0, size = array.length; i < size - 1; ++i) { 22 | boolean swapped = false; 23 | for (int j = 0; j < size - 1 - i; ++j) { 24 | swapped = less(array[j], array[j + 1]) && swap(array, j, j + 1); 25 | } 26 | if (!swapped) { 27 | break; 28 | } 29 | } 30 | return array; 31 | } 32 | 33 | // Driver Program 34 | public static void main(String[] args) { 35 | 36 | // Integer Input 37 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 38 | BubbleSort bubbleSort = new BubbleSort(); 39 | bubbleSort.sort(integers); 40 | 41 | // Output => 231, 78, 54, 23, 12, 9, 6, 4, 1 42 | print(integers); 43 | 44 | // String Input 45 | String[] strings = {"c", "a", "e", "b", "d"}; 46 | //Output => e, d, c, b, a 47 | print(bubbleSort.sort(strings)); 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /DynamicProgramming/KadaneAlgorithm.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Program to implement Kadane’s Algorithm to 7 | * calculate maximum contiguous subarray sum of an array 8 | * Time Complexity: O(n) 9 | * 10 | * @author Nishita Aggarwal 11 | */ 12 | 13 | public class KadaneAlgorithm { 14 | 15 | /** 16 | * This method implements Kadane's Algorithm 17 | * 18 | * @param arr The input array 19 | * @return The maximum contiguous subarray sum of the array 20 | */ 21 | static int largestContiguousSum(int arr[]) { 22 | int i, len = arr.length, cursum = 0, maxsum = Integer.MIN_VALUE; 23 | if (len == 0) //empty array 24 | return 0; 25 | for (i = 0; i < len; i++) { 26 | cursum += arr[i]; 27 | if (cursum > maxsum) { 28 | maxsum = cursum; 29 | } 30 | if (cursum <= 0) { 31 | cursum = 0; 32 | } 33 | } 34 | return maxsum; 35 | } 36 | 37 | /** 38 | * Main method 39 | * 40 | * @param args Command line arguments 41 | */ 42 | public static void main(String[] args) { 43 | Scanner sc = new Scanner(System.in); 44 | int n, arr[], i; 45 | n = sc.nextInt(); 46 | arr = new int[n]; 47 | for (i = 0; i < n; i++) { 48 | arr[i] = sc.nextInt(); 49 | } 50 | int maxContSum = largestContiguousSum(arr); 51 | System.out.println(maxContSum); 52 | sc.close(); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /DataStructures/Trees/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Trees; 2 | 3 | public class LevelOrderTraversal { 4 | 5 | class Node { 6 | int data; 7 | Node left, right; 8 | 9 | public Node(int item) { 10 | data = item; 11 | left = right = null; 12 | } 13 | } 14 | 15 | // Root of the Binary Tree 16 | Node root; 17 | 18 | public LevelOrderTraversal() { 19 | root = null; 20 | } 21 | 22 | /* function to print level order traversal of tree*/ 23 | void printLevelOrder() { 24 | int h = height(root); 25 | int i; 26 | for (i = 1; i <= h; i++) 27 | printGivenLevel(root, i); 28 | } 29 | 30 | /* Compute the "height" of a tree -- the number of 31 | nodes along the longest path from the root node 32 | down to the farthest leaf node.*/ 33 | int height(Node root) { 34 | if (root == null) 35 | return 0; 36 | else { 37 | /** 38 | * Return the height of larger subtree 39 | */ 40 | return Math.max(height(root.left), height(root.right)) + 1; 41 | } 42 | } 43 | 44 | /* Print nodes at the given level */ 45 | void printGivenLevel(Node root, int level) { 46 | if (root == null) 47 | return; 48 | if (level == 1) 49 | System.out.print(root.data + " "); 50 | else if (level > 1) { 51 | printGivenLevel(root.left, level - 1); 52 | printGivenLevel(root.right, level - 1); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /DynamicProgramming/EggDropping.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * DynamicProgramming solution for the Egg Dropping Puzzle 5 | */ 6 | public class EggDropping { 7 | 8 | // min trials with n eggs and m floors 9 | 10 | private static int minTrials(int n, int m) { 11 | 12 | int[][] eggFloor = new int[n + 1][m + 1]; 13 | int result, x; 14 | 15 | for (int i = 1; i <= n; i++) { 16 | eggFloor[i][0] = 0; // Zero trial for zero floor. 17 | eggFloor[i][1] = 1; // One trial for one floor 18 | } 19 | 20 | // j trials for only 1 egg 21 | 22 | for (int j = 1; j <= m; j++) 23 | eggFloor[1][j] = j; 24 | 25 | // Using bottom-up approach in DP 26 | 27 | for (int i = 2; i <= n; i++) { 28 | for (int j = 2; j <= m; j++) { 29 | eggFloor[i][j] = Integer.MAX_VALUE; 30 | for (x = 1; x <= j; x++) { 31 | result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); 32 | 33 | // choose min of all values for particular x 34 | if (result < eggFloor[i][j]) 35 | eggFloor[i][j] = result; 36 | } 37 | } 38 | } 39 | 40 | return eggFloor[n][m]; 41 | } 42 | 43 | public static void main(String args[]) { 44 | int n = 2, m = 4; 45 | // result outputs min no. of trials in worst case for n eggs and m floors 46 | int result = minTrials(n, m); 47 | System.out.println(result); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /DataStructures/Lists/Merge_K_SortedLinkedlist.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Lists; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.PriorityQueue; 6 | 7 | /** 8 | * @author Arun Pandey (https://github.com/pandeyarun709) 9 | */ 10 | public class Merge_K_SortedLinkedlist { 11 | 12 | /** 13 | * This function merge K sorted LinkedList 14 | * 15 | * @param a array of LinkedList 16 | * @param N size of array 17 | * @return node 18 | */ 19 | Node mergeKList(Node[] a, int N) { 20 | // Min Heap 21 | PriorityQueue min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); 22 | 23 | // adding head of all linkedList in min heap 24 | min.addAll(Arrays.asList(a).subList(0, N)); 25 | 26 | // Make new head among smallest heads in K linkedList 27 | Node head = min.poll(); 28 | min.add(head.next); 29 | Node curr = head; 30 | 31 | // merging LinkedList 32 | while (!min.isEmpty()) { 33 | 34 | Node temp = min.poll(); 35 | curr.next = temp; 36 | curr = temp; 37 | 38 | // Add Node in min Heap only if temp.next is not null 39 | if (temp.next != null) { 40 | min.add(temp.next); 41 | } 42 | } 43 | 44 | return head; 45 | } 46 | 47 | private class Node { 48 | private int data; 49 | private Node next; 50 | 51 | public Node(int d) { 52 | this.data = d; 53 | next = null; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /DataStructures/Stacks/DecimalToAnyUsingStack.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Stacks; 2 | 3 | import java.util.Stack; 4 | 5 | public class DecimalToAnyUsingStack { 6 | public static void main(String[] args) { 7 | assert convert(0, 2).equals("0"); 8 | assert convert(30, 2).equals("11110"); 9 | assert convert(30, 8).equals("36"); 10 | assert convert(30, 10).equals("30"); 11 | assert convert(30, 16).equals("1E"); 12 | } 13 | 14 | /** 15 | * Convert decimal number to another radix 16 | * 17 | * @param number the number to be converted 18 | * @param radix the radix 19 | * @return another radix 20 | * @throws ArithmeticException if number or radius is invalid 21 | */ 22 | private static String convert(int number, int radix) { 23 | if (radix < 2 || radix > 16) { 24 | throw new ArithmeticException( 25 | String.format("Invalid input -> number:%d,radius:%d", number, radix)); 26 | } 27 | char[] tables = { 28 | '0', '1', '2', '3', '4', 29 | '5', '6', '7', '8', '9', 30 | 'A', 'B', 'C', 'D', 'E', 'F' 31 | }; 32 | Stack bits = new Stack<>(); 33 | do { 34 | bits.push(tables[number % radix]); 35 | number = number / radix; 36 | } while (number != 0); 37 | 38 | StringBuilder result = new StringBuilder(); 39 | while (!bits.isEmpty()) { 40 | result.append(bits.pop()); 41 | } 42 | return result.toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Sorts/BogoSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import java.util.Random; 4 | 5 | 6 | /** 7 | * @author Podshivalov Nikita (https://github.com/nikitap492) 8 | * @see SortAlgorithm 9 | */ 10 | public class BogoSort implements SortAlgorithm { 11 | 12 | private static final Random random = new Random(); 13 | 14 | 15 | private static > boolean isSorted(T array[]) { 16 | for (int i = 0; i < array.length - 1; i++) { 17 | if (SortUtils.less(array[i + 1], array[i])) return false; 18 | } 19 | return true; 20 | } 21 | 22 | // Randomly shuffles the array 23 | private static void nextPermutation(T array[]) { 24 | int length = array.length; 25 | 26 | for (int i = 0; i < array.length; i++) { 27 | int randomIndex = i + random.nextInt(length - i); 28 | SortUtils.swap(array, randomIndex, i); 29 | } 30 | } 31 | 32 | public > T[] sort(T array[]) { 33 | while (!isSorted(array)) { 34 | nextPermutation(array); 35 | } 36 | return array; 37 | } 38 | 39 | // Driver Program 40 | public static void main(String[] args) { 41 | // Integer Input 42 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 43 | 44 | BogoSort bogoSort = new BogoSort(); 45 | 46 | // print a sorted array 47 | SortUtils.print(bogoSort.sort(integers)); 48 | 49 | // String Input 50 | String[] strings = {"c", "a", "e", "b", "d"}; 51 | 52 | SortUtils.print(bogoSort.sort(strings)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Sorts/RadixSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import java.util.Arrays; 4 | 5 | class RadixSort { 6 | 7 | private static int getMax(int arr[], int n) { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | private static void countSort(int arr[], int n, int exp) { 16 | int output[] = new int[n]; 17 | int i; 18 | int count[] = new int[10]; 19 | Arrays.fill(count, 0); 20 | 21 | for (i = 0; i < n; i++) 22 | count[(arr[i] / exp) % 10]++; 23 | 24 | for (i = 1; i < 10; i++) 25 | count[i] += count[i - 1]; 26 | 27 | for (i = n - 1; i >= 0; i--) { 28 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 29 | count[(arr[i] / exp) % 10]--; 30 | } 31 | 32 | for (i = 0; i < n; i++) 33 | arr[i] = output[i]; 34 | } 35 | 36 | private static void radixsort(int arr[], int n) { 37 | 38 | int m = getMax(arr, n); 39 | 40 | 41 | for (int exp = 1; m / exp > 0; exp *= 10) 42 | countSort(arr, n, exp); 43 | } 44 | 45 | 46 | static void print(int arr[], int n) { 47 | for (int i = 0; i < n; i++) 48 | System.out.print(arr[i] + " "); 49 | } 50 | 51 | 52 | public static void main(String[] args) { 53 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 54 | int n = arr.length; 55 | radixsort(arr, n); 56 | print(arr, n); 57 | } 58 | } 59 | // Written by James Mc Dermott(theycallmemac) 60 | -------------------------------------------------------------------------------- /DataStructures/Heaps/Heap.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Heaps; 2 | 3 | /** 4 | * Interface common to heap data structures.
5 | *

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

11 | *

All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in 12 | * O(log n) time.

13 | * 14 | * @author Nicolas Renard 15 | */ 16 | public interface Heap { 17 | 18 | /** 19 | * @return the top element in the heap, the one with lowest key for min-heap or with 20 | * the highest key for max-heap 21 | * @throws EmptyHeapException if heap is empty 22 | */ 23 | HeapElement getElement() throws EmptyHeapException; 24 | 25 | /** 26 | * Inserts an element in the heap. Adds it to then end and toggle it until it finds its 27 | * right position. 28 | * 29 | * @param element an instance of the HeapElement class. 30 | */ 31 | void insertElement(HeapElement element); 32 | 33 | /** 34 | * Delete an element in the heap. 35 | * 36 | * @param elementIndex int containing the position in the heap of the element to be deleted. 37 | */ 38 | void deleteElement(int elementIndex); 39 | 40 | } -------------------------------------------------------------------------------- /Others/CountWords.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * You enter a string into this program, and it will return how many words were 7 | * in that particular string 8 | * 9 | * @author Marcus 10 | */ 11 | public class CountWords { 12 | 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.println("Enter your text: "); 16 | String str = input.nextLine(); 17 | 18 | System.out.println("Your text has " + wordCount(str) + " word(s)"); 19 | System.out.println("Your text has " + secondaryWordCount(str) + " word(s)"); 20 | input.close(); 21 | } 22 | 23 | private static int wordCount(String s) { 24 | if (s == null || s.isEmpty()) 25 | return 0; 26 | return s.trim().split("[\\s]+").length; 27 | } 28 | 29 | /** 30 | * counts the number of words in a sentence but ignores all potential 31 | * non-alphanumeric characters that do not represent a word. runs in O(n) where 32 | * n is the length of s 33 | * 34 | * @param s String: sentence with word(s) 35 | * @return int: number of words 36 | */ 37 | private static int secondaryWordCount(String s) { 38 | if (s == null || s.isEmpty()) 39 | return 0; 40 | StringBuilder sb = new StringBuilder(); 41 | for (char c : s.toCharArray()) { 42 | if (Character.isLetter(c) || Character.isDigit(c)) 43 | sb.append(c); 44 | } 45 | s = sb.toString(); 46 | return s.trim().split("[\\s]+").length; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Others/Palindrome.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | class Palindrome { 4 | 5 | private String reverseString(String x) { // *helper method 6 | StringBuilder output = new StringBuilder(x); 7 | return output.reverse().toString(); 8 | } 9 | 10 | public boolean FirstWay(String x) { // *palindrome method, returns true if palindrome 11 | if (x == null || x.length() <= 1) 12 | return true; 13 | return x.equalsIgnoreCase(reverseString(x)); 14 | } 15 | 16 | public boolean SecondWay(String x) { 17 | if (x.length() == 0 || x.length() == 1) 18 | return true; 19 | 20 | if (x.charAt(0) != x.charAt(x.length() - 1)) 21 | return false; 22 | 23 | return SecondWay(x.substring(1, x.length() - 1)); 24 | } 25 | 26 | /** 27 | * This method ignores all non-alphanumeric characters and case runs in O(n) 28 | * where n is the length of s 29 | * 30 | * @param s String to check 31 | * @return true if s is palindrome else false 32 | */ 33 | public boolean isPalindrome(String s) { 34 | s = s.toLowerCase().trim(); 35 | StringBuilder sb = new StringBuilder(); 36 | for (char c : s.toCharArray()) { 37 | if (Character.isLetter(c) || Character.isDigit(c)) 38 | sb.append(c); 39 | } 40 | s = sb.toString(); 41 | int start = 0; 42 | int end = s.length() - 1; 43 | while (start <= end) { 44 | if (s.charAt(start++) != s.charAt(end--)) 45 | return false; 46 | 47 | } 48 | return true; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Maths/GCD.java: -------------------------------------------------------------------------------- 1 | package Maths; 2 | 3 | /** 4 | * This is Euclid's algorithm which is used to find the greatest common denominator 5 | * Overide function name gcd 6 | * 7 | * @author Oskar Enmalm 3/10/17 8 | */ 9 | public class GCD { 10 | 11 | /** 12 | * get greatest common divisor 13 | * 14 | * @param num1 the first number 15 | * @param num2 the second number 16 | * @return gcd 17 | */ 18 | public static int gcd(int num1, int num2) { 19 | if (num1 < 0 || num2 < 0) { 20 | throw new ArithmeticException(); 21 | } 22 | 23 | if (num1 == 0 || num2 == 0) { 24 | return Math.abs(num1 - num2); 25 | } 26 | 27 | while (num1 % num2 != 0) { 28 | int remainder = num1 % num2; 29 | num1 = num2; 30 | num2 = remainder; 31 | } 32 | return num2; 33 | } 34 | 35 | /** 36 | * get greatest common divisor in array 37 | * 38 | * @param number contains number 39 | * @return gcd 40 | */ 41 | public static int gcd(int[] number) { 42 | int result = number[0]; 43 | for (int i = 1; i < number.length; i++) 44 | // call gcd function (input two value) 45 | result = gcd(result, number[i]); 46 | 47 | return result; 48 | } 49 | 50 | public static void main(String[] args) { 51 | int[] myIntArray = {4, 16, 32}; 52 | 53 | // call gcd function (input array) 54 | System.out.println(gcd(myIntArray)); // => 4 55 | System.out.printf("gcd(40,24)=%d gcd(24,40)=%d\n", gcd(40, 24), gcd(24, 40)); // => 8 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Conversions/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.*; 4 | 5 | public class RomanToInteger { 6 | 7 | private static Map map = new HashMap() {{ 8 | put('I', 1); 9 | put('V', 5); 10 | put('X', 10); 11 | put('L', 50); 12 | put('C', 100); 13 | put('D', 500); 14 | put('M', 1000); 15 | }}; 16 | 17 | /** 18 | * This function convert Roman number into Integer 19 | * 20 | * @param A Roman number string 21 | * @return integer 22 | */ 23 | public static int romanToInt(String A) { 24 | 25 | char prev = ' '; 26 | 27 | int sum = 0; 28 | 29 | int newPrev = 0; 30 | for (int i = A.length() - 1; i >= 0; i--) { 31 | char c = A.charAt(i); 32 | 33 | if (prev != ' ') { 34 | // checking current Number greater then previous or not 35 | newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev; 36 | } 37 | 38 | int currentNum = map.get(c); 39 | 40 | // if current number greater then prev max previous then add 41 | if (currentNum >= newPrev) { 42 | sum += currentNum; 43 | } else { 44 | // subtract upcoming number until upcoming number not greater then prev max 45 | sum -= currentNum; 46 | } 47 | 48 | prev = c; 49 | } 50 | 51 | return sum; 52 | } 53 | 54 | public static void main(String[] args) { 55 | int sum = romanToInt("MDCCCIV"); 56 | System.out.println(sum); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Sorts/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.less; 4 | import static Sorts.SortUtils.print; 5 | 6 | /** 7 | * @author Varun Upadhyay (https://github.com/varunu28) 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | */ 10 | 11 | class InsertionSort implements SortAlgorithm { 12 | 13 | /** 14 | * This method implements the Generic Insertion Sort 15 | * Sorts the array in increasing order 16 | * 17 | * @param array The array to be sorted 18 | **/ 19 | 20 | @Override 21 | public > T[] sort(T[] array) { 22 | for (int j = 1; j < array.length; j++) { 23 | 24 | // Picking up the key(Card) 25 | T key = array[j]; 26 | int i = j - 1; 27 | 28 | while (i >= 0 && less(key, array[i])) { 29 | array[i + 1] = array[i]; 30 | i--; 31 | } 32 | // Placing the key (Card) at its correct position in the sorted subarray 33 | array[i + 1] = key; 34 | } 35 | return array; 36 | } 37 | 38 | // Driver Program 39 | public static void main(String[] args) { 40 | // Integer Input 41 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 42 | 43 | InsertionSort sort = new InsertionSort(); 44 | 45 | sort.sort(integers); 46 | 47 | // Output => 1 4 6 9 12 23 54 78 231 48 | print(integers); 49 | 50 | // String Input 51 | String[] strings = {"c", "a", "e", "b", "d"}; 52 | 53 | sort.sort(strings); 54 | 55 | //Output => a b c d e 56 | print(strings); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Others/InsertDeleteInArray.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.*; 4 | 5 | public class InsertDeleteInArray { 6 | 7 | public static void main(String[] args) { 8 | Scanner s = new Scanner(System.in); // Input statement 9 | System.out.println("Enter the size of the array"); 10 | int size = s.nextInt(); 11 | int a[] = new int[size]; 12 | int i; 13 | 14 | // To enter the initial elements 15 | for (i = 0; i < size; i++) { 16 | System.out.println("Enter the element"); 17 | a[i] = s.nextInt(); 18 | } 19 | 20 | // To insert a new element(we are creating a new array) 21 | System.out.println("Enter the index at which the element should be inserted"); 22 | int insert_pos = s.nextInt(); 23 | System.out.println("Enter the element to be inserted"); 24 | int ins = s.nextInt(); 25 | int size2 = size + 1; 26 | int b[] = new int[size2]; 27 | for (i = 0; i < size2; i++) { 28 | if (i <= insert_pos) { 29 | b[i] = a[i]; 30 | } else { 31 | b[i] = a[i - 1]; 32 | } 33 | } 34 | b[insert_pos] = ins; 35 | for (i = 0; i < size2; i++) { 36 | System.out.println(b[i]); 37 | } 38 | 39 | // To delete an element given the index 40 | System.out.println("Enter the index at which element is to be deleted"); 41 | int del_pos = s.nextInt(); 42 | for (i = del_pos; i < size2 - 1; i++) { 43 | b[i] = b[i + 1]; 44 | } 45 | for (i = 0; i < size2 - 1; i++) 46 | System.out.println(b[i]); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Others/Armstrong.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * A utility to check if a given number is armstrong or not. Armstrong number is 7 | * a number that is equal to the sum of cubes of its digits for example 0, 1, 8 | * 153, 370, 371, 407 etc. For example 153 = 1^3 + 5^3 +3^3 9 | * 10 | * @author mani manasa mylavarapu 11 | */ 12 | public class Armstrong { 13 | static Scanner scan; 14 | 15 | public static void main(String[] args) { 16 | scan = new Scanner(System.in); 17 | int n = inputInt("please enter the number"); 18 | boolean isArmstrong = checkIfANumberIsAmstrongOrNot(n); 19 | if (isArmstrong) { 20 | System.out.println("the number is armstrong"); 21 | } else { 22 | System.out.println("the number is not armstrong"); 23 | } 24 | } 25 | 26 | /** 27 | * Checks whether a given number is an armstrong number or not. Armstrong 28 | * number is a number that is equal to the sum of cubes of its digits for 29 | * example 0, 1, 153, 370, 371, 407 etc. 30 | * 31 | * @param number 32 | * @return boolean 33 | */ 34 | public static boolean checkIfANumberIsAmstrongOrNot(int number) { 35 | int remainder, sum = 0, temp = 0; 36 | temp = number; 37 | while (number > 0) { 38 | remainder = number % 10; 39 | sum = sum + (remainder * remainder * remainder); 40 | number = number / 10; 41 | } 42 | return sum == temp; 43 | } 44 | 45 | private static int inputInt(String string) { 46 | System.out.print(string); 47 | return Integer.parseInt(scan.nextLine()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Misc/PalindromePrime.java: -------------------------------------------------------------------------------- 1 | package Misc; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PalindromePrime { 6 | 7 | public static void main(String[] args) { // Main funtion 8 | Scanner in = new Scanner(System.in); 9 | System.out.println("Enter the quantity of First Palindromic Primes you want"); 10 | int n = in.nextInt(); // Input of how many first pallindromic prime we want 11 | functioning(n); // calling function - functioning 12 | } 13 | 14 | public static boolean prime(int num) { // checking if number is prime or not 15 | for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) { 16 | if (num % divisor == 0) { 17 | return false; // false if not prime 18 | } 19 | } 20 | return true; // True if prime 21 | } 22 | 23 | public static int reverse(int n) { // Returns the reverse of the number 24 | int reverse = 0; 25 | while (n != 0) { 26 | reverse *= 10; 27 | reverse += n % 10; 28 | n /= 10; 29 | } 30 | return reverse; 31 | } 32 | 33 | public static void functioning(int y) { 34 | if (y == 0) return; 35 | System.out.print(2 + "\n"); // print the first Palindromic Prime 36 | int count = 1; 37 | int num = 3; 38 | while (count < y) { 39 | if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same 40 | count++; // counts check when to terminate while loop 41 | System.out.print(num + "\n"); // print the Palindromic Prime 42 | } 43 | num += 2; // inrease iterator value by two 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Sorts/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | * @author Podshivalov Nikita (https://github.com/nikitap492) 6 | * @see SortAlgorithm 7 | */ 8 | 9 | public class SelectionSort implements SortAlgorithm { 10 | 11 | /** 12 | * This method implements the Generic Selection Sort 13 | * 14 | * @param arr The array to be sorted 15 | * Sorts the array in increasing order 16 | **/ 17 | @Override 18 | public > T[] sort(T[] arr) { 19 | int n = arr.length; 20 | for (int i = 0; i < n - 1; i++) { 21 | // Initial index of min 22 | int min = i; 23 | 24 | for (int j = i + 1; j < n; j++) { 25 | if (SortUtils.less(arr[j], arr[min])) { 26 | min = j; 27 | } 28 | } 29 | 30 | // Swapping if index of min is changed 31 | if (min != i) { 32 | SortUtils.swap(arr, i, min); 33 | } 34 | } 35 | 36 | return arr; 37 | } 38 | 39 | // Driver Program 40 | public static void main(String[] args) { 41 | 42 | Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 43 | 44 | SelectionSort selectionSort = new SelectionSort(); 45 | 46 | Integer[] sorted = selectionSort.sort(arr); 47 | 48 | // Output => 1 4 6 9 12 23 54 78 231 49 | SortUtils.print(sorted); 50 | 51 | // String Input 52 | String[] strings = {"c", "a", "e", "b", "d"}; 53 | String[] sortedStrings = selectionSort.sort(strings); 54 | 55 | //Output => a b c d e 56 | SortUtils.print(sortedStrings); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Conversions/DecimalToBinary.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Decimal number to a Binary number 7 | * 8 | * @author Unknown 9 | */ 10 | class DecimalToBinary { 11 | 12 | /** 13 | * Main Method 14 | * 15 | * @param args Command Line Arguments 16 | */ 17 | public static void main(String args[]) { 18 | conventionalConversion(); 19 | bitwiseConversion(); 20 | } 21 | 22 | /** 23 | * This method converts a decimal number 24 | * to a binary number using a conventional 25 | * algorithm. 26 | */ 27 | public static void conventionalConversion() { 28 | int n, b = 0, c = 0, d; 29 | Scanner input = new Scanner(System.in); 30 | System.out.printf("Conventional conversion.\n\tEnter the decimal number: "); 31 | n = input.nextInt(); 32 | while (n != 0) { 33 | d = n % 2; 34 | b = b + d * (int) Math.pow(10, c++); 35 | n /= 2; 36 | } //converting decimal to binary 37 | System.out.println("\tBinary number: " + b); 38 | } 39 | 40 | /** 41 | * This method converts a decimal number 42 | * to a binary number using a bitwise 43 | * algorithm 44 | */ 45 | public static void bitwiseConversion() { 46 | int n, b = 0, c = 0, d; 47 | Scanner input = new Scanner(System.in); 48 | System.out.printf("Bitwise conversion.\n\tEnter the decimal number: "); 49 | n = input.nextInt(); 50 | while (n != 0) { 51 | d = (n & 1); 52 | b += d * (int) Math.pow(10, c++); 53 | n >>= 1; 54 | } 55 | System.out.println("\tBinary number: " + b); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Others/ReturnSubsequence.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ReturnSubsequence { 6 | public static void main(String[] args) { 7 | System.out.println("Enter String: "); 8 | Scanner s = new Scanner(System.in); 9 | String givenString = s.next(); //given string 10 | String[] subsequence = returnSubsequence(givenString); //calling returnSubsequence() function 11 | System.out.println("Subsequences : "); 12 | //print the given array of subsequences 13 | for (int i = 0; i < subsequence.length; i++) { 14 | System.out.println(subsequence[i]); 15 | } 16 | } 17 | 18 | /** 19 | * @param givenString 20 | * @return subsequence 21 | */ 22 | private static String[] returnSubsequence(String givenString) { 23 | if (givenString.length() == 0) // If string is empty we will create an array of size=1 and insert "" (Empty string) in it 24 | { 25 | String[] ans = new String[1]; 26 | ans[0] = ""; 27 | return ans; 28 | 29 | } 30 | String[] SmallAns = returnSubsequence(givenString.substring(1)); //recursive call to get subsequences of substring starting from index position=1 31 | 32 | String[] ans = new String[2 * SmallAns.length];// Our answer will be an array off string of size=2*SmallAns 33 | int i = 0; 34 | for (; i < SmallAns.length; i++) { 35 | ans[i] = SmallAns[i]; //Copying all the strings present in SmallAns to ans string array 36 | } 37 | for (int k = 0; k < SmallAns.length; k++) { 38 | ans[k + SmallAns.length] = givenString.charAt(0) + SmallAns[k]; // Insert character at index=0 of the given substring in front of every string in SmallAns 39 | } 40 | return ans; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Conversions/BinaryToHexadecimal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Converts any Binary Number to a Hexadecimal Number 7 | * 8 | * @author Nishita Aggarwal 9 | */ 10 | public class BinaryToHexadecimal { 11 | 12 | /** 13 | * This method converts a binary number to 14 | * a hexadecimal number. 15 | * 16 | * @param binary The binary number 17 | * @return The hexadecimal number 18 | */ 19 | static String binToHex(int binary) { 20 | //hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15 21 | HashMap hm = new HashMap<>(); 22 | //String to store hexadecimal code 23 | String hex = ""; 24 | int i; 25 | for (i = 0; i < 10; i++) { 26 | hm.put(i, String.valueOf(i)); 27 | } 28 | for (i = 10; i < 16; i++) hm.put(i, String.valueOf((char) ('A' + i - 10))); 29 | int currbit; 30 | while (binary != 0) { 31 | int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits 32 | for (i = 0; i < 4; i++) { 33 | currbit = binary % 10; 34 | binary = binary / 10; 35 | code4 += currbit * Math.pow(2, i); 36 | } 37 | hex = hm.get(code4) + hex; 38 | } 39 | return hex; 40 | } 41 | 42 | /** 43 | * Main method 44 | * 45 | * @param args Command line arguments 46 | */ 47 | public static void main(String[] args) { 48 | Scanner sc = new Scanner(System.in); 49 | System.out.println("Enter binary number:"); 50 | int binary = sc.nextInt(); 51 | String hex = binToHex(binary); 52 | System.out.println("Hexadecimal Code:" + hex); 53 | sc.close(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /DynamicProgramming/LongestValidParentheses.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Given a string containing just the characters '(' and ')', find the length of 7 | * the longest valid (well-formed) parentheses substring. 8 | * 9 | * @author Libin Yang (https://github.com/yanglbme) 10 | * @since 2018/10/5 11 | */ 12 | 13 | public class LongestValidParentheses { 14 | 15 | public static int getLongestValidParentheses(String s) { 16 | if (s == null || s.length() < 2) { 17 | return 0; 18 | } 19 | char[] chars = s.toCharArray(); 20 | int n = chars.length; 21 | int[] res = new int[n]; 22 | res[0] = 0; 23 | res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; 24 | 25 | int max = res[1]; 26 | 27 | for (int i = 2; i < n; ++i) { 28 | if (chars[i] == ')') { 29 | if (chars[i - 1] == '(') { 30 | res[i] = res[i - 2] + 2; 31 | } else { 32 | int index = i - res[i - 1] - 1; 33 | if (index >= 0 && chars[index] == '(') { 34 | // ()(()) 35 | res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); 36 | } 37 | } 38 | } 39 | max = Math.max(max, res[i]); 40 | } 41 | 42 | return max; 43 | 44 | } 45 | 46 | public static void main(String[] args) { 47 | Scanner sc = new Scanner(System.in); 48 | 49 | while (true) { 50 | String str = sc.nextLine(); 51 | if ("quit".equals(str)) { 52 | break; 53 | } 54 | int len = getLongestValidParentheses(str); 55 | System.out.println(len); 56 | 57 | } 58 | 59 | sc.close(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Others/KMP.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | /** 4 | * Implementation of Knuth–Morris–Pratt algorithm 5 | * Usage: see the main function for an example 6 | */ 7 | public class KMP { 8 | //a working example 9 | public static void main(String[] args) { 10 | final String haystack = "AAAAABAAABA"; //This is the full string 11 | final String needle = "AAAA"; //This is the substring that we want to find 12 | KMPmatcher(haystack, needle); 13 | } 14 | 15 | // find the starting index in string haystack[] that matches the search word P[] 16 | public static void KMPmatcher(final String haystack, final String needle) { 17 | final int m = haystack.length(); 18 | final int n = needle.length(); 19 | final int[] pi = computePrefixFunction(needle); 20 | int q = 0; 21 | for (int i = 0; i < m; i++) { 22 | while (q > 0 && haystack.charAt(i) != needle.charAt(q)) { 23 | q = pi[q - 1]; 24 | } 25 | 26 | if (haystack.charAt(i) == needle.charAt(q)) { 27 | q++; 28 | } 29 | 30 | if (q == n) { 31 | System.out.println("Pattern starts: " + (i + 1 - n)); 32 | q = pi[q - 1]; 33 | } 34 | } 35 | } 36 | 37 | // return the prefix function 38 | private static int[] computePrefixFunction(final String P) { 39 | final int n = P.length(); 40 | final int[] pi = new int[n]; 41 | pi[0] = 0; 42 | int q = 0; 43 | for (int i = 1; i < n; i++) { 44 | while (q > 0 && P.charAt(q) != P.charAt(i)) { 45 | q = pi[q - 1]; 46 | } 47 | 48 | if (P.charAt(q) == P.charAt(i)) { 49 | q++; 50 | } 51 | 52 | pi[i] = q; 53 | 54 | } 55 | return pi; 56 | } 57 | } -------------------------------------------------------------------------------- /DynamicProgramming/LevenshteinDistance.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * @author Kshitij VERMA (github.com/kv19971) 5 | * LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance) 6 | */ 7 | 8 | public class LevenshteinDistance { 9 | private static int minimum(int a, int b, int c) { 10 | if (a < b && a < c) { 11 | return a; 12 | } else if (b < a && b < c) { 13 | return b; 14 | } else { 15 | return c; 16 | } 17 | } 18 | 19 | private static int calculate_distance(String a, String b) { 20 | int len_a = a.length() + 1; 21 | int len_b = b.length() + 1; 22 | int[][] distance_mat = new int[len_a][len_b]; 23 | for (int i = 0; i < len_a; i++) { 24 | distance_mat[i][0] = i; 25 | } 26 | for (int j = 0; j < len_b; j++) { 27 | distance_mat[0][j] = j; 28 | } 29 | for (int i = 0; i < len_a; i++) { 30 | for (int j = 0; j < len_b; j++) { 31 | int cost; 32 | if (a.charAt(i) == b.charAt(j)) { 33 | cost = 0; 34 | } else { 35 | cost = 1; 36 | } 37 | distance_mat[i][j] = minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1]) + cost; 38 | 39 | 40 | } 41 | 42 | } 43 | return distance_mat[len_a - 1][len_b - 1]; 44 | 45 | } 46 | 47 | public static void main(String[] args) { 48 | String a = ""; // enter your string here 49 | String b = ""; // enter your string here 50 | 51 | System.out.print("Levenshtein distance between " + a + " and " + b + " is: "); 52 | System.out.println(calculate_distance(a, b)); 53 | 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Conversions/OctalToHexadecimal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Octal Number to HexaDecimal 7 | * 8 | * @author Tanmay Joshi 9 | */ 10 | public class OctalToHexadecimal { 11 | 12 | /** 13 | * This method converts a Octal number to a decimal number 14 | * 15 | * @param s The Octal Number 16 | * @return The Decimal number 17 | */ 18 | public static int OctToDec(String s) { 19 | int i = 0; 20 | for (int j = 0; j < s.length(); j++) { 21 | char num = s.charAt(j); 22 | num -= '0'; 23 | i *= 8; 24 | i += num; 25 | } 26 | return i; 27 | } 28 | 29 | /** 30 | * This method converts a Decimal number to a Hexadecimal number 31 | * 32 | * @param d The Decimal Number 33 | * @return The Hexadecimal number 34 | */ 35 | public static String DecimalToHex(int d) { 36 | String digits = "0123456789ABCDEF"; 37 | if (d <= 0) 38 | return "0"; 39 | String hex = ""; 40 | while (d > 0) { 41 | int digit = d % 16; 42 | hex = digits.charAt(digit) + hex; 43 | d = d / 16; 44 | } 45 | return hex; 46 | } 47 | 48 | 49 | public static void main(String args[]) { 50 | 51 | Scanner input = new Scanner(System.in); 52 | System.out.print("Enter the Octal number: "); 53 | // Take octal number as input from user in a string 54 | String oct = input.next(); 55 | 56 | // Pass the octal number to function and get converted deciaml form 57 | int decimal = OctToDec(oct); 58 | 59 | // Pass the decimla number to function and get converted Hex form of the number 60 | String hex = DecimalToHex(decimal); 61 | System.out.println("The Hexadecimal equivalant is: " + hex); 62 | } 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Conversions/AnyBaseToDecimal.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | */ 6 | 7 | // Driver program 8 | public class AnyBaseToDecimal { 9 | public static void main(String[] args) { 10 | assert convertToDecimal("1010", 2) == Integer.valueOf("1010", 2); 11 | assert convertToDecimal("777", 8) == Integer.valueOf("777", 8); 12 | assert convertToDecimal("999", 10) == Integer.valueOf("999", 10); 13 | assert convertToDecimal("ABCDEF", 16) == Integer.valueOf("ABCDEF", 16); 14 | assert convertToDecimal("XYZ", 36) == Integer.valueOf("XYZ", 36); 15 | } 16 | 17 | /** 18 | * Convert any radix to decimal number 19 | * 20 | * @param s the string to be convert 21 | * @param radix the radix 22 | * @return decimal of bits 23 | * @throws NumberFormatException if {@code bits} or {@code radix} is invalid 24 | */ 25 | public static int convertToDecimal(String s, int radix) { 26 | int num = 0; 27 | int pow = 1; 28 | 29 | for (int i = s.length() - 1; i >= 0; i--) { 30 | int digit = valOfChar(s.charAt(i)); 31 | if (digit >= radix) { 32 | throw new NumberFormatException("For input string " + s); 33 | } 34 | num += valOfChar(s.charAt(i)) * pow; 35 | pow *= radix; 36 | } 37 | return num; 38 | } 39 | 40 | /** 41 | * Convert character to integer 42 | * 43 | * @param c the character 44 | * @return represented digit of given character 45 | * @throws NumberFormatException if {@code ch} is not UpperCase or Digit character. 46 | */ 47 | public static int valOfChar(char c) { 48 | if (!(Character.isUpperCase(c) || Character.isDigit(c))) { 49 | throw new NumberFormatException("invalid character :" + c); 50 | } 51 | return Character.isDigit(c) ? c - '0' : c - 'A' + 10; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /DataStructures/Lists/MergeSortedArrayList.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Lists; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author https://github.com/shellhub 8 | */ 9 | 10 | public class MergeSortedArrayList { 11 | public static void main(String[] args) { 12 | List listA = new ArrayList<>(); 13 | List listB = new ArrayList<>(); 14 | List listC = new ArrayList<>(); 15 | 16 | /* init ListA and List B */ 17 | for (int i = 1; i <= 10; i += 2) { 18 | listA.add(i); /* listA: [1, 3, 5, 7, 9] */ 19 | listB.add(i + 1); /* listB: [2, 4, 6, 8, 10] */ 20 | } 21 | 22 | /* merge listA and listB to listC */ 23 | merge(listA, listB, listC); 24 | 25 | System.out.println("listA: " + listA); 26 | System.out.println("listB: " + listB); 27 | System.out.println("listC: " + listC); 28 | } 29 | 30 | /** 31 | * merge two sorted ArrayList 32 | * 33 | * @param listA the first list to merge 34 | * @param listB the second list to merge 35 | * @param listC the result list after merging 36 | */ 37 | public static void merge(List listA, List listB, List listC) { 38 | int pa = 0; /* the index of listA */ 39 | int pb = 0; /* the index of listB */ 40 | 41 | while (pa < listA.size() && pb < listB.size()) { 42 | if (listA.get(pa) <= listB.get(pb)) { 43 | listC.add(listA.get(pa++)); 44 | } else { 45 | listC.add(listB.get(pb++)); 46 | } 47 | } 48 | 49 | /* copy left element of listA to listC */ 50 | while (pa < listA.size()) { 51 | listC.add(listA.get(pa++)); 52 | } 53 | 54 | /* copy left element of listB to listC */ 55 | while (pb < listB.size()) { 56 | listC.add(listB.get(pb++)); 57 | } 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /DynamicProgramming/LongestIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @author Afrizal Fikri (https://github.com/icalF) 7 | */ 8 | public class LongestIncreasingSubsequence { 9 | public static void main(String[] args) { 10 | 11 | Scanner sc = new Scanner(System.in); 12 | int n = sc.nextInt(); 13 | 14 | int ar[] = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | ar[i] = sc.nextInt(); 17 | } 18 | 19 | System.out.println(LIS(ar)); 20 | } 21 | 22 | private static int upperBound(int[] ar, int l, int r, int key) { 23 | while (l < r - 1) { 24 | int m = (l + r) / 2; 25 | if (ar[m] >= key) 26 | r = m; 27 | else 28 | l = m; 29 | } 30 | 31 | return r; 32 | } 33 | 34 | private static int LIS(int[] array) { 35 | int N = array.length; 36 | if (N == 0) 37 | return 0; 38 | 39 | int[] tail = new int[N]; 40 | 41 | // always points empty slot in tail 42 | int length = 1; 43 | 44 | tail[0] = array[0]; 45 | for (int i = 1; i < N; i++) { 46 | 47 | // new smallest value 48 | if (array[i] < tail[0]) 49 | tail[0] = array[i]; 50 | 51 | // array[i] extends largest subsequence 52 | else if (array[i] > tail[length - 1]) 53 | tail[length++] = array[i]; 54 | 55 | // array[i] will become end candidate of an existing subsequence or 56 | // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i] 57 | // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it) 58 | else 59 | tail[upperBound(tail, -1, length - 1, array[i])] = array[i]; 60 | } 61 | 62 | return length; 63 | } 64 | } -------------------------------------------------------------------------------- /Searches/LinearSearch.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | import java.util.Random; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * Linear search is the easiest search algorithm 8 | * It works with sorted and unsorted arrays (an binary search works only with sorted array) 9 | * This algorithm just compares all elements of an array to find a value 10 | *

11 | * Worst-case performance O(n) 12 | * Best-case performance O(1) 13 | * Average performance O(n) 14 | * Worst-case space complexity 15 | * 16 | * @author Varun Upadhyay (https://github.com/varunu28) 17 | * @author Podshivalov Nikita (https://github.com/nikitap492) 18 | * @see BinarySearch 19 | * @see SearchAlgorithm 20 | */ 21 | 22 | public class LinearSearch implements SearchAlgorithm { 23 | 24 | /** 25 | * Generic Linear search method 26 | * 27 | * @param array List to be searched 28 | * @param value Key being searched for 29 | * @return Location of the key 30 | */ 31 | @Override 32 | public > int find(T[] array, T value) { 33 | for (int i = 0; i < array.length; i++) { 34 | if (array[i].compareTo(value) == 0) { 35 | return i; 36 | } 37 | } 38 | return -1; 39 | } 40 | 41 | 42 | public static void main(String[] args) { 43 | //just generate data 44 | Random r = new Random(); 45 | int size = 200; 46 | int maxElement = 100; 47 | Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[]::new); 48 | 49 | 50 | //the element that should be found 51 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 52 | 53 | LinearSearch search = new LinearSearch(); 54 | int atIndex = search.find(integers, shouldBeFound); 55 | 56 | System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" 57 | , shouldBeFound, integers[atIndex], atIndex, size)); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Sorts/CocktailShakerSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | /** 4 | * @author Mateus Bizzo (https://github.com/MattBizzo) 5 | * @author Podshivalov Nikita (https://github.com/nikitap492) 6 | */ 7 | 8 | class CocktailShakerSort implements SortAlgorithm { 9 | 10 | /** 11 | * This method implements the Generic Cocktail Shaker Sort 12 | * 13 | * @param array The array to be sorted 14 | * Sorts the array in increasing order 15 | **/ 16 | 17 | @Override 18 | public > T[] sort(T[] array) { 19 | 20 | int length = array.length; 21 | int left = 0; 22 | int right = length - 1; 23 | int swappedLeft, swappedRight; 24 | while (left < right) { 25 | // front 26 | swappedRight = 0; 27 | for (int i = left; i < right; i++) { 28 | if (SortUtils.less(array[i + 1], array[i])) { 29 | SortUtils.swap(array, i, i + 1); 30 | swappedRight = i; 31 | } 32 | } 33 | // back 34 | right = swappedRight; 35 | swappedLeft = length - 1; 36 | for (int j = right; j > left; j--) { 37 | if (SortUtils.less(array[j], array[j - 1])) { 38 | SortUtils.swap(array, j - 1, j); 39 | swappedLeft = j; 40 | } 41 | } 42 | left = swappedLeft; 43 | } 44 | return array; 45 | 46 | } 47 | 48 | // Driver Program 49 | public static void main(String[] args) { 50 | // Integer Input 51 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 52 | CocktailShakerSort shakerSort = new CocktailShakerSort(); 53 | 54 | // Output => 1 4 6 9 12 23 54 78 231 55 | SortUtils.print(shakerSort.sort(integers)); 56 | 57 | // String Input 58 | String[] strings = {"c", "a", "e", "b", "d"}; 59 | SortUtils.print(shakerSort.sort(strings)); 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /Others/ReverseStackUsingRecursion.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | /* Program to reverse a Stack using Recursion*/ 4 | 5 | 6 | import java.util.Stack; 7 | 8 | public class ReverseStackUsingRecursion { 9 | 10 | //Stack 11 | private static Stack stack = new Stack<>(); 12 | 13 | //Main function 14 | public static void main(String[] args) { 15 | //To Create a Dummy Stack containing integers from 0-9 16 | for (int i = 0; i < 10; i++) { 17 | stack.push(i); 18 | } 19 | System.out.println("STACK"); 20 | 21 | //To print that dummy Stack 22 | for (int k = 9; k >= 0; k--) { 23 | System.out.println(k); 24 | } 25 | 26 | //Reverse Function called 27 | reverseUsingRecursion(stack); 28 | 29 | System.out.println("REVERSED STACK : "); 30 | //To print reversed stack 31 | while (!stack.isEmpty()) { 32 | System.out.println(stack.pop()); 33 | } 34 | 35 | 36 | } 37 | 38 | //Function Used to reverse Stack Using Recursion 39 | private static void reverseUsingRecursion(Stack stack) { 40 | if (stack.isEmpty()) // If stack is empty then return 41 | { 42 | return; 43 | } 44 | /* All items are stored in call stack until we reach the end*/ 45 | 46 | int temptop = stack.peek(); 47 | stack.pop(); 48 | reverseUsingRecursion(stack); //Recursion call 49 | insertAtEnd(temptop); // Insert items held in call stack one by one into stack 50 | } 51 | 52 | //Function used to insert element at the end of stack 53 | private static void insertAtEnd(int temptop) { 54 | if (stack.isEmpty()) { 55 | stack.push(temptop); // If stack is empty push the element 56 | } else { 57 | int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/ 58 | stack.pop(); 59 | 60 | insertAtEnd(temptop); //Recursive call 61 | 62 | stack.push(temp); 63 | } 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /ciphers/Vigenere.java: -------------------------------------------------------------------------------- 1 | package ciphers; 2 | 3 | /** 4 | * A Java implementation of Vigenere Cipher. 5 | * @author straiffix 6 | */ 7 | 8 | 9 | public class Vigenere { 10 | 11 | public static String encrypt(final String message, final String key) 12 | { 13 | 14 | String result = ""; 15 | 16 | for (int i = 0, j = 0; i < message.length(); i++) { 17 | char c = message.charAt(i); 18 | if (Character.isLetter(c)){ 19 | if(Character.isUpperCase(c)) { 20 | result += (char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'); 21 | 22 | } else { 23 | result += (char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'); 24 | 25 | } 26 | } else { 27 | result+=c; 28 | } 29 | j = ++j % key.length(); 30 | } 31 | return result; 32 | } 33 | 34 | public static String decrypt( final String message, final String key) 35 | { 36 | String result =""; 37 | 38 | for(int i = 0, j = 0; i < message.length(); i++){ 39 | 40 | char c = message.charAt(i); 41 | if (Character.isLetter(c)){ 42 | if(Character.isUpperCase(c)) { 43 | result += ((char)('Z'-(25-(c-key.toUpperCase().charAt(j)))%26)); 44 | 45 | } else { 46 | result += ((char)('z'-(25-(c-key.toLowerCase().charAt(j)))%26)); 47 | 48 | } 49 | } else { 50 | result+=c; 51 | } 52 | 53 | j = ++j % key.length(); 54 | 55 | } 56 | return result; 57 | } 58 | public static void main (String [] args){ 59 | String text="Hello World!"; 60 | String key="itsakey"; 61 | System.out.println(text); 62 | String ciphertext=encrypt(text, key); 63 | System.out.println(ciphertext); 64 | System.out.println(decrypt(ciphertext, key)); 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Conversions/HexToOct.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Hexadecimal Number to Octal 7 | * 8 | * @author Tanmay Joshi 9 | */ 10 | public class HexToOct { 11 | /** 12 | * This method converts a Hexadecimal number to a decimal number 13 | * 14 | * @param s The Hexadecimal Number 15 | * @return The Decimal number 16 | */ 17 | public static int hex2decimal(String s) { 18 | String str = "0123456789ABCDEF"; 19 | s = s.toUpperCase(); 20 | int val = 0; 21 | for (int i = 0; i < s.length(); i++) { 22 | char a = s.charAt(i); 23 | int n = str.indexOf(a); 24 | val = 16 * val + n; 25 | } 26 | return val; 27 | } 28 | 29 | /** 30 | * This method converts a Decimal number to a octal number 31 | * 32 | * @param q The Decimal Number 33 | * @return The Octal number 34 | */ 35 | public static int decimal2octal(int q) { 36 | int now; 37 | int i = 1; 38 | int octnum = 0; 39 | while (q > 0) { 40 | now = q % 8; 41 | octnum = (now * (int) (Math.pow(10, i))) + octnum; 42 | q /= 8; 43 | i++; 44 | } 45 | octnum /= 10; 46 | return octnum; 47 | } 48 | 49 | /** 50 | * Main method that gets the hex input from user and converts it into octal. 51 | * @param args arguments 52 | */ 53 | public static void main(String args[]) { 54 | String hexadecnum; 55 | int decnum, octalnum; 56 | Scanner scan = new Scanner(System.in); 57 | 58 | System.out.print("Enter Hexadecimal Number : "); 59 | hexadecnum = scan.nextLine(); 60 | 61 | // first convert hexadecimal to decimal 62 | decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum 63 | 64 | // convert decimal to octal 65 | octalnum = decimal2octal(decnum); 66 | System.out.println("Number in octal: " + octalnum); 67 | 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Misc/heap_sort.java: -------------------------------------------------------------------------------- 1 | package Misc; 2 | 3 | public class heap_sort { 4 | public void sort(int[] arr) { 5 | int n = arr.length; 6 | 7 | // Build heap (rearrange array) 8 | for (int i = n / 2 - 1; i >= 0; i--) 9 | heapify(arr, n, i); 10 | 11 | // One by one extract an element from heap 12 | for (int i = n - 1; i >= 0; i--) { 13 | // Move current root to end 14 | int temp = arr[0]; 15 | arr[0] = arr[i]; 16 | arr[i] = temp; 17 | 18 | // call max heapify on the reduced heap 19 | heapify(arr, i, 0); 20 | } 21 | } 22 | 23 | // To heapify a subtree rooted with node i which is 24 | // an index in arr[]. n is size of heap 25 | void heapify(int[] arr, int n, int i) { 26 | int largest = i; // Initialize largest as root 27 | int l = 2 * i + 1; // left = 2*i + 1 28 | int r = 2 * i + 2; // right = 2*i + 2 29 | 30 | // If left child is larger than root 31 | if (l < n && arr[l] > arr[largest]) 32 | largest = l; 33 | 34 | // If right child is larger than largest so far 35 | if (r < n && arr[r] > arr[largest]) 36 | largest = r; 37 | 38 | // If largest is not root 39 | if (largest != i) { 40 | int swap = arr[i]; 41 | arr[i] = arr[largest]; 42 | arr[largest] = swap; 43 | 44 | // Recursively heapify the affected sub-tree 45 | heapify(arr, n, largest); 46 | } 47 | } 48 | 49 | /* A utility function to print array of size n */ 50 | static void printArray(int[] arr) { 51 | int n = arr.length; 52 | for (int i = 0; i < n; ++i) 53 | System.out.print(arr[i] + " "); 54 | System.out.println(); 55 | } 56 | 57 | // Driver program 58 | public static void main(String args[]) { 59 | int arr[] = {12, 11, 13, 5, 6, 7}; 60 | int n = arr.length; 61 | 62 | heap_sort ob = new heap_sort(); 63 | ob.sort(arr); 64 | 65 | System.out.println("Sorted array is"); 66 | printArray(arr); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Conversions/DecimalToAnyBase.java: -------------------------------------------------------------------------------- 1 | package Conversions; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.util.ArrayList; 6 | 7 | /** 8 | * 9 | * @author Varun Upadhyay (https://github.com/varunu28) 10 | * 11 | */ 12 | 13 | // Driver Program 14 | public class DecimalToAnyBase { 15 | public static void main (String[] args) throws Exception{ 16 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 17 | System.out.println("Enter the decimal input below: "); 18 | int decInput = Integer.parseInt(br.readLine()); 19 | System.out.println(); 20 | 21 | System.out.println("Enter the base below: "); 22 | int base = Integer.parseInt(br.readLine()); 23 | System.out.println(); 24 | 25 | System.out.println("Decimal Input" + " is: " + decInput); 26 | System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); 27 | 28 | br.close(); 29 | } 30 | 31 | /** 32 | * This method produces a String value of any given input decimal in any base 33 | * @param inp Decimal of which we need the value in base in String format 34 | * @return string format of the converted value in the given base 35 | */ 36 | 37 | public static String convertToAnyBase(int inp, int base) { 38 | ArrayList charArr = new ArrayList<>(); 39 | 40 | while (inp > 0) { 41 | charArr.add(reVal(inp%base)); 42 | inp /= base; 43 | } 44 | 45 | StringBuilder str = new StringBuilder(charArr.size()); 46 | 47 | for(Character ch: charArr) 48 | { 49 | str.append(ch); 50 | } 51 | 52 | return str.reverse().toString(); 53 | } 54 | 55 | /** 56 | * This method produces character value of the input integer and returns it 57 | * @param num integer of which we need the character value of 58 | * @return character value of input integer 59 | */ 60 | 61 | public static char reVal(int num) { 62 | if (num >= 0 && num <= 9) 63 | return (char)(num + '0'); 64 | else 65 | return (char)(num - 10 + 'A'); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Others/LinearCongruentialGenerator.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | /*** 4 | * A pseudorandom number generator. 5 | * 6 | * @author Tobias Carryer 7 | * @date October 10, 2017 8 | */ 9 | public class LinearCongruentialGenerator { 10 | 11 | private double a, c, m, previousValue; 12 | 13 | /*** 14 | * These parameters are saved and used when nextNumber() is called. 15 | * The current timestamp in milliseconds is used as the seed. 16 | * 17 | * @param multiplier 18 | * @param increment 19 | * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32. 20 | */ 21 | public LinearCongruentialGenerator(double multiplier, double increment, double modulo) { 22 | this(System.currentTimeMillis(), multiplier, increment, modulo); 23 | } 24 | 25 | /*** 26 | * These parameters are saved and used when nextNumber() is called. 27 | * 28 | * @param seed 29 | * @param multiplier 30 | * @param increment 31 | * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32. 32 | */ 33 | public LinearCongruentialGenerator(double seed, double multiplier, double increment, double modulo) { 34 | this.previousValue = seed; 35 | this.a = multiplier; 36 | this.c = increment; 37 | this.m = modulo; 38 | } 39 | 40 | /** 41 | * The smallest number that can be generated is zero. 42 | * The largest number that can be generated is modulo-1. modulo is set in the constructor. 43 | * 44 | * @return a pseudorandom number. 45 | */ 46 | public double nextNumber() { 47 | previousValue = (a * previousValue + c) % m; 48 | return previousValue; 49 | } 50 | 51 | public static void main(String[] args) { 52 | // Show the LCG in action. 53 | // Decisive proof that the LCG works could be made by adding each number 54 | // generated to a Set while checking for duplicates. 55 | LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0)); 56 | for (int i = 0; i < 512; i++) { 57 | System.out.println(lcg.nextNumber()); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Sorts/SortUtils.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * The class contains util methods 8 | * 9 | * @author Podshivalov Nikita (https://github.com/nikitap492) 10 | **/ 11 | final class SortUtils { 12 | 13 | /** 14 | * Helper method for swapping places in array 15 | * 16 | * @param array The array which elements we want to swap 17 | * @param idx index of the first element 18 | * @param idy index of the second element 19 | */ 20 | static boolean swap(T[] array, int idx, int idy) { 21 | T swap = array[idx]; 22 | array[idx] = array[idy]; 23 | array[idy] = swap; 24 | return true; 25 | } 26 | 27 | 28 | /** 29 | * This method checks if first element is less then the other element 30 | * 31 | * @param v first element 32 | * @param w second element 33 | * @return true if the first element is less then the second element 34 | */ 35 | static > boolean less(T v, T w) { 36 | return v.compareTo(w) < 0; 37 | } 38 | 39 | 40 | /** 41 | * Just print list 42 | * 43 | * @param toPrint - a list which should be printed 44 | */ 45 | static void print(List toPrint) { 46 | toPrint.stream() 47 | .map(Object::toString) 48 | .map(str -> str + " ") 49 | .forEach(System.out::print); 50 | 51 | System.out.println(); 52 | } 53 | 54 | 55 | /** 56 | * Prints an array 57 | * 58 | * @param toPrint - the array which should be printed 59 | */ 60 | static void print(Object[] toPrint) { 61 | System.out.println(Arrays.toString(toPrint)); 62 | } 63 | 64 | 65 | /** 66 | * Swaps all position from {@param left} to @{@param right} for {@param array} 67 | * 68 | * @param array is an array 69 | * @param left is a left flip border of the array 70 | * @param right is a right flip border of the array 71 | */ 72 | static > void flip(T[] array, int left, int right) { 73 | while (left <= right) { 74 | swap(array, left++, right--); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Sorts/CombSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.*; 4 | 5 | 6 | /** 7 | * Comb Sort algorithm implementation 8 | *

9 | * Best-case performance O(n * log(n)) 10 | * Worst-case performance O(n ^ 2) 11 | * Worst-case space complexity O(1) 12 | *

13 | * Comb sort improves on bubble sort. 14 | * 15 | * @author Sandeep Roy (https://github.com/sandeeproy99) 16 | * @author Podshivalov Nikita (https://github.com/nikitap492) 17 | * @see BubbleSort 18 | * @see SortAlgorithm 19 | */ 20 | class CombSort implements SortAlgorithm { 21 | 22 | // To find gap between elements 23 | private int nextGap(int gap) { 24 | // Shrink gap by Shrink factor 25 | gap = (gap * 10) / 13; 26 | return (gap < 1) ? 1 : gap; 27 | } 28 | 29 | /** 30 | * Function to sort arr[] using Comb 31 | * 32 | * @param arr - an array should be sorted 33 | * @return sorted array 34 | */ 35 | @Override 36 | public > T[] sort(T arr[]) { 37 | int size = arr.length; 38 | 39 | // initialize gap 40 | int gap = size; 41 | 42 | // Initialize swapped as true to make sure that loop runs 43 | boolean swapped = true; 44 | 45 | // Keep running while gap is more than 1 and last iteration caused a swap 46 | while (gap != 1 || swapped) { 47 | // Find next gap 48 | gap = nextGap(gap); 49 | 50 | // Initialize swapped as false so that we can check if swap happened or not 51 | swapped = false; 52 | 53 | // Compare all elements with current gap 54 | for (int i = 0; i < size - gap; i++) { 55 | if (less(arr[i + gap], arr[i])) { 56 | // Swap arr[i] and arr[i+gap] 57 | swapped = swap(arr, i, i + gap); 58 | } 59 | } 60 | } 61 | return arr; 62 | } 63 | 64 | // Driver method 65 | public static void main(String args[]) { 66 | CombSort ob = new CombSort(); 67 | Integer arr[] = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0}; 68 | ob.sort(arr); 69 | 70 | System.out.println("sorted array"); 71 | print(arr); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /MinimizingLateness/MinimizingLateness.java: -------------------------------------------------------------------------------- 1 | package MinimizingLateness; 2 | 3 | 4 | import java.io.BufferedReader; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.util.StringTokenizer; 8 | 9 | public class MinimizingLateness { 10 | 11 | private static class Schedule { // Schedule class 12 | int t = 0; // Time required for the operation to be performed 13 | int d = 0; // Time the job should be completed 14 | int s = 0; // Start time of the task 15 | int f = 0; // End time of the operation 16 | 17 | public Schedule(int t, int d) { 18 | this.t = t; 19 | this.d = d; 20 | } 21 | } 22 | 23 | public static void main(String[] args) throws IOException { 24 | StringTokenizer token; 25 | 26 | BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt")); 27 | String ch = in.readLine(); 28 | if (ch == null || ch.isEmpty()) { 29 | return; 30 | } 31 | int indexCount = Integer.parseInt(ch); 32 | System.out.println("Input Data : "); 33 | System.out.println(indexCount); // number of operations 34 | Schedule[] array = new Schedule[indexCount]; // Create an array to hold the operation 35 | int i = 0; 36 | while ((ch = in.readLine()) != null) { 37 | token = new StringTokenizer(ch, " "); 38 | // Include the time required for the operation to be performed in the array and the time it should be completed. 39 | array[i] = new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken())); 40 | i++; 41 | System.out.println(array[i - 1].t + " " + array[i - 1].d); 42 | } 43 | 44 | int tryTime = 0; // Total time worked 45 | int lateness = 0; // Lateness 46 | for (int j = 0; j < indexCount - 1; j++) { 47 | array[j].s = tryTime; // Start time of the task 48 | array[j].f = tryTime + array[j].t; // Time finished 49 | tryTime = tryTime + array[j].t; // Add total work time 50 | // Lateness 51 | lateness = lateness + Math.max(0, tryTime - array[j].d); 52 | } 53 | System.out.println(); 54 | System.out.println("Output Data : "); 55 | System.out.println(lateness); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /DataStructures/Lists/CircleLinkedList.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Lists; 2 | 3 | public class CircleLinkedList { 4 | private static class Node { 5 | Node next; 6 | E value; 7 | 8 | private Node(E value, Node next) { 9 | this.value = value; 10 | this.next = next; 11 | } 12 | } 13 | 14 | //For better O.O design this should be private allows for better black box design 15 | private int size; 16 | //this will point to dummy node; 17 | private Node head; 18 | 19 | //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty; 20 | public CircleLinkedList() { 21 | //creation of the dummy node 22 | head = new Node(null, head); 23 | size = 0; 24 | } 25 | 26 | // getter for the size... needed because size is private. 27 | public int getSize() { 28 | return size; 29 | } 30 | 31 | // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really. 32 | public void append(E value) { 33 | if (value == null) { 34 | // we do not want to add null elements to the list. 35 | throw new NullPointerException("Cannot add null element to the list"); 36 | } 37 | //head.next points to the last element; 38 | head.next = new Node(value, head); 39 | size++; 40 | } 41 | 42 | public E remove(int pos) { 43 | if (pos > size || pos < 0) { 44 | //catching errors 45 | throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); 46 | } 47 | //we need to keep track of the element before the element we want to remove we can see why bellow. 48 | Node before = head; 49 | for (int i = 1; i <= pos; i++) { 50 | before = before.next; 51 | } 52 | Node destroy = before.next; 53 | E saved = destroy.value; 54 | // assigning the next reference to the the element following the element we want to remove... the last element will be assigned to the head. 55 | before.next = before.next.next; 56 | // scrubbing 57 | destroy = null; 58 | size--; 59 | return saved; 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /Sorts/CycleSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.less; 4 | import static Sorts.SortUtils.print; 5 | 6 | /** 7 | * @author Podshivalov Nikita (https://github.com/nikitap492) 8 | */ 9 | class CycleSort implements SortAlgorithm { 10 | 11 | @Override 12 | public > T[] sort(T[] arr) { 13 | int n = arr.length; 14 | 15 | // traverse array elements 16 | for (int j = 0; j <= n - 2; j++) { 17 | // initialize item as starting point 18 | T item = arr[j]; 19 | 20 | // Find position where we put the item. 21 | int pos = j; 22 | for (int i = j + 1; i < n; i++) 23 | if (less(arr[i], item)) pos++; 24 | 25 | // If item is already in correct position 26 | if (pos == j) continue; 27 | 28 | // ignore all duplicate elements 29 | while (item.compareTo(arr[pos]) == 0) 30 | pos += 1; 31 | 32 | // put the item to it's right position 33 | if (pos != j) { 34 | item = replace(arr, pos, item); 35 | } 36 | 37 | // Rotate rest of the cycle 38 | while (pos != j) { 39 | pos = j; 40 | 41 | // Find position where we put the element 42 | for (int i = j + 1; i < n; i++) 43 | if (less(arr[i], item)) { 44 | pos += 1; 45 | } 46 | 47 | 48 | // ignore all duplicate elements 49 | while (item.compareTo(arr[pos]) == 0) 50 | pos += 1; 51 | 52 | // put the item to it's right position 53 | if (item != arr[pos]) { 54 | item = replace(arr, pos, item); 55 | } 56 | } 57 | } 58 | 59 | return arr; 60 | } 61 | 62 | private > T replace(T[] arr, int pos, T item) { 63 | T temp = item; 64 | item = arr[pos]; 65 | arr[pos] = temp; 66 | return item; 67 | } 68 | 69 | 70 | public static void main(String[] args) { 71 | Integer arr[] = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; 72 | CycleSort cycleSort = new CycleSort(); 73 | cycleSort.sort(arr); 74 | 75 | System.out.println("After sort : "); 76 | print(arr); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /DynamicProgramming/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | class LongestCommonSubsequence { 4 | 5 | public static String getLCS(String str1, String str2) { 6 | 7 | //At least one string is null 8 | if (str1 == null || str2 == null) 9 | return null; 10 | 11 | //At least one string is empty 12 | if (str1.length() == 0 || str2.length() == 0) 13 | return ""; 14 | 15 | String[] arr1 = str1.split(""); 16 | String[] arr2 = str2.split(""); 17 | 18 | //lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2 19 | int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1]; 20 | 21 | for (int i = 0; i < arr1.length + 1; i++) 22 | lcsMatrix[i][0] = 0; 23 | for (int j = 1; j < arr2.length + 1; j++) 24 | lcsMatrix[0][j] = 0; 25 | for (int i = 1; i < arr1.length + 1; i++) { 26 | for (int j = 1; j < arr2.length + 1; j++) { 27 | if (arr1[i - 1].equals(arr2[j - 1])) { 28 | lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1; 29 | } else { 30 | lcsMatrix[i][j] = lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] ? lcsMatrix[i - 1][j] : lcsMatrix[i][j - 1]; 31 | } 32 | } 33 | } 34 | return lcsString(str1, str2, lcsMatrix); 35 | } 36 | 37 | public static String lcsString(String str1, String str2, int[][] lcsMatrix) { 38 | StringBuilder lcs = new StringBuilder(); 39 | int i = str1.length(), 40 | j = str2.length(); 41 | while (i > 0 && j > 0) { 42 | if (str1.charAt(i - 1) == str2.charAt(j - 1)) { 43 | lcs.append(str1.charAt(i - 1)); 44 | i--; 45 | j--; 46 | } else if (lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1]) { 47 | i--; 48 | } else { 49 | j--; 50 | } 51 | } 52 | return lcs.reverse().toString(); 53 | } 54 | 55 | public static void main(String[] args) { 56 | String str1 = "DSGSHSRGSRHTRD"; 57 | String str2 = "DATRGAGTSHS"; 58 | String lcs = getLCS(str1, str2); 59 | 60 | //Print LCS 61 | if (lcs != null) { 62 | System.out.println("String 1: " + str1); 63 | System.out.println("String 2: " + str2); 64 | System.out.println("LCS: " + lcs); 65 | System.out.println("LCS length: " + lcs.length()); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /DynamicProgramming/FordFulkerson.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | import java.util.Vector; 6 | 7 | public class FordFulkerson { 8 | final static int INF = 987654321; 9 | // edges 10 | static int V; 11 | static int[][] capacity, flow; 12 | 13 | public static void main(String[] args) { 14 | System.out.println("V : 6"); 15 | V = 6; 16 | capacity = new int[V][V]; 17 | 18 | capacity[0][1] = 12; 19 | capacity[0][3] = 13; 20 | capacity[1][2] = 10; 21 | capacity[2][3] = 13; 22 | capacity[2][4] = 3; 23 | capacity[2][5] = 15; 24 | capacity[3][2] = 7; 25 | capacity[3][4] = 15; 26 | capacity[4][5] = 17; 27 | 28 | System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); 29 | } 30 | 31 | private static int networkFlow(int source, int sink) { 32 | flow = new int[V][V]; 33 | int totalFlow = 0; 34 | while (true) { 35 | Vector parent = new Vector<>(V); 36 | for (int i = 0; i < V; i++) 37 | parent.add(-1); 38 | Queue q = new LinkedList<>(); 39 | parent.set(source, source); 40 | q.add(source); 41 | while (!q.isEmpty() && parent.get(sink) == -1) { 42 | int here = q.peek(); 43 | q.poll(); 44 | for (int there = 0; there < V; ++there) 45 | if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { 46 | q.add(there); 47 | parent.set(there, here); 48 | } 49 | } 50 | if (parent.get(sink) == -1) 51 | break; 52 | 53 | int amount = INF; 54 | String printer = "path : "; 55 | StringBuilder sb = new StringBuilder(); 56 | for (int p = sink; p != source; p = parent.get(p)) { 57 | amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); 58 | sb.append(p + "-"); 59 | } 60 | sb.append(source); 61 | for (int p = sink; p != source; p = parent.get(p)) { 62 | flow[parent.get(p)][p] += amount; 63 | flow[p][parent.get(p)] -= amount; 64 | } 65 | totalFlow += amount; 66 | printer += sb.reverse() + " / max flow : " + totalFlow; 67 | System.out.println(printer); 68 | } 69 | 70 | return totalFlow; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Searches/SaddlebackSearch.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Program to perform Saddleback Search 7 | * Given a sorted 2D array(elements are sorted across every row and column, assuming ascending order) 8 | * of size n*m we can search a given element in O(n+m) 9 | *

10 | * we start from bottom left corner 11 | * if the current element is greater than the given element then we move up 12 | * else we move right 13 | * Sample Input: 14 | * 5 5 ->Dimensions 15 | * -10 -5 -3 4 9 16 | * -6 -2 0 5 10 17 | * -4 -1 1 6 12 18 | * 2 3 7 8 13 19 | * 100 120 130 140 150 20 | * 140 ->element to be searched 21 | * output: 4 3 // first value is row, second one is column 22 | * 23 | * @author Nishita Aggarwal 24 | */ 25 | public class SaddlebackSearch { 26 | 27 | /** 28 | * This method performs Saddleback Search 29 | * 30 | * @param arr The **Sorted** array in which we will search the element. 31 | * @param row the current row. 32 | * @param col the current column. 33 | * @param key the element that we want to search for. 34 | * @return The index(row and column) of the element if found. 35 | * Else returns -1 -1. 36 | */ 37 | private static int[] find(int arr[][], int row, int col, int key) { 38 | 39 | //array to store the answer row and column 40 | int ans[] = {-1, -1}; 41 | if (row < 0 || col >= arr[row].length) { 42 | return ans; 43 | } 44 | if (arr[row][col] == key) { 45 | ans[0] = row; 46 | ans[1] = col; 47 | return ans; 48 | } 49 | //if the current element is greater than the given element then we move up 50 | else if (arr[row][col] > key) { 51 | return find(arr, row - 1, col, key); 52 | } 53 | //else we move right 54 | return find(arr, row, col + 1, key); 55 | } 56 | 57 | /** 58 | * Main method 59 | * 60 | * @param args Command line arguments 61 | */ 62 | public static void main(String[] args) { 63 | // TODO Auto-generated method stub 64 | Scanner sc = new Scanner(System.in); 65 | int arr[][]; 66 | int i, j, rows = sc.nextInt(), col = sc.nextInt(); 67 | arr = new int[rows][col]; 68 | for (i = 0; i < rows; i++) { 69 | for (j = 0; j < col; j++) { 70 | arr[i][j] = sc.nextInt(); 71 | } 72 | } 73 | int ele = sc.nextInt(); 74 | //we start from bottom left corner 75 | int ans[] = find(arr, rows - 1, 0, ele); 76 | System.out.println(ans[0] + " " + ans[1]); 77 | sc.close(); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /DataStructures/Queues/GenericArrayListQueue.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Queues; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * This class implements a GenericArrayListQueue. 7 | *

8 | * A GenericArrayListQueue data structure functions the same as any specific-typed queue. 9 | * The GenericArrayListQueue holds elemets of types to-be-specified at runtime. 10 | * The elements that are added first are the first to be removed (FIFO) 11 | * New elements are added to the back/rear of the queue. 12 | * 13 | */ 14 | public class GenericArrayListQueue { 15 | /** 16 | * The generic ArrayList for the queue 17 | * T is the generic element 18 | */ 19 | ArrayList _queue = new ArrayList(); 20 | 21 | /** 22 | * Checks if the queue has elements (not empty) 23 | * 24 | * @return True if the queue has elements. False otherwise. 25 | */ 26 | private boolean hasElements() { 27 | return !_queue.isEmpty(); 28 | } 29 | 30 | /** 31 | * Checks what's at the front of the queue 32 | * 33 | * @return If queue is not empty, element at the front of the queue. Otherwise, null 34 | */ 35 | public T peek() { 36 | T result = null; 37 | if(this.hasElements()) { result = _queue.get(0); } 38 | return result; 39 | } 40 | 41 | /** 42 | * Inserts an element of type T to the queue. 43 | * 44 | * @param element of type T to be added 45 | * @return True if the element was added successfully 46 | */ 47 | public boolean add(T element) { 48 | return _queue.add(element); 49 | } 50 | 51 | /** 52 | * Retrieve what's at the front of the queue 53 | * 54 | * @return If queue is not empty, element retrieved. Otherwise, null 55 | */ 56 | public T poll() { 57 | T result = null; 58 | if(this.hasElements()) { result = _queue.remove(0); } 59 | return result; 60 | } 61 | 62 | /** 63 | * Main method 64 | * 65 | * @param args Command line arguments 66 | */ 67 | public static void main(String[] args) { 68 | GenericArrayListQueue queue = new GenericArrayListQueue(); 69 | System.out.println("Running..."); 70 | assert queue.peek() == null; 71 | assert queue.poll() == null; 72 | assert queue.add(1) == true; 73 | assert queue.peek() == 1; 74 | assert queue.add(2) == true; 75 | assert queue.peek() == 1; 76 | assert queue.poll() == 1; 77 | assert queue.peek() == 2; 78 | assert queue.poll() == 2; 79 | assert queue.peek() == null; 80 | assert queue.poll() == null; 81 | System.out.println("Finished."); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Searches/InterpolationSearch.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | import java.util.stream.IntStream; 6 | 7 | import static java.lang.String.format; 8 | 9 | /** 10 | * Interpolation search algorithm implementation 11 | *

12 | * Worst-case performance O(n) 13 | * Best-case performance O(1) 14 | * Average performance O(log(log(n))) if the elements are uniformly distributed if not O(n) 15 | * Worst-case space complexity O(1) 16 | * 17 | * @author Podshivalov Nikita (https://github.com/nikitap492) 18 | */ 19 | class InterpolationSearch { 20 | 21 | 22 | /** 23 | * @param array is a sorted array 24 | * @param key is a value what shoulb be found in the array 25 | * @return an index if the array contains the key unless -1 26 | */ 27 | public int find(int array[], int key) { 28 | // Find indexes of two corners 29 | int start = 0, end = (array.length - 1); 30 | 31 | // Since array is sorted, an element present 32 | // in array must be in range defined by corner 33 | while (start <= end && key >= array[start] && key <= array[end]) { 34 | // Probing the position with keeping 35 | // uniform distribution in mind. 36 | int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); 37 | 38 | // Condition of target found 39 | if (array[pos] == key) 40 | return pos; 41 | 42 | // If key is larger, key is in upper part 43 | if (array[pos] < key) 44 | start = pos + 1; 45 | 46 | // If key is smaller, x is in lower part 47 | else 48 | end = pos - 1; 49 | } 50 | return -1; 51 | } 52 | 53 | // Driver method 54 | public static void main(String[] args) { 55 | Random r = new Random(); 56 | int size = 100; 57 | int maxElement = 100000; 58 | int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); 59 | 60 | 61 | //the element that should be found 62 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 63 | 64 | InterpolationSearch search = new InterpolationSearch(); 65 | int atIndex = search.find(integers, shouldBeFound); 66 | 67 | System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" 68 | , shouldBeFound, integers[atIndex], atIndex, size)); 69 | 70 | 71 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 72 | System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 73 | } 74 | } 75 | 76 | -------------------------------------------------------------------------------- /DataStructures/Graphs/Cycles.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Graphs; 2 | 3 | import java.util.Scanner; 4 | import java.util.ArrayList; 5 | 6 | 7 | class Cycle { 8 | 9 | private int nodes, edges; 10 | private int[][] adjacencyMatrix; 11 | private boolean[] visited; 12 | ArrayList> cycles = new ArrayList>(); 13 | private boolean[] finalCycles; 14 | 15 | public Cycle() { 16 | Scanner in = new Scanner(System.in); 17 | System.out.print("Enter the no. of nodes: "); 18 | nodes = in.nextInt(); 19 | System.out.print("Enter the no. of Edges: "); 20 | edges = in.nextInt(); 21 | 22 | adjacencyMatrix = new int[nodes][nodes]; 23 | visited = new boolean[nodes]; 24 | 25 | for (int i = 0; i < nodes; i++) { 26 | visited[i] = false; 27 | } 28 | 29 | System.out.println("Enter the details of each edges "); 30 | 31 | for (int i = 0; i < edges; i++) { 32 | int start, end; 33 | start = in.nextInt(); 34 | end = in.nextInt(); 35 | adjacencyMatrix[start][end] = 1; 36 | } 37 | 38 | } 39 | 40 | public void start() { 41 | for (int i = 0; i < nodes; i++) { 42 | ArrayList temp = new ArrayList<>(); 43 | dfs(i, i, temp); 44 | for (int j = 0; j < nodes; j++) { 45 | adjacencyMatrix[i][j] = 0; 46 | adjacencyMatrix[j][i] = 0; 47 | } 48 | } 49 | } 50 | 51 | private void dfs(Integer start, Integer curr, ArrayList temp) { 52 | temp.add(curr); 53 | visited[curr] = true; 54 | for (int i = 0; i < nodes; i++) { 55 | if (adjacencyMatrix[curr][i] == 1) { 56 | if (i == start) { 57 | cycles.add(new ArrayList(temp)); 58 | } else { 59 | if (!visited[i]) { 60 | dfs(start, i, temp); 61 | } 62 | } 63 | } 64 | } 65 | 66 | if (temp.size() > 0) { 67 | temp.remove(temp.size() - 1); 68 | } 69 | visited[curr] = false; 70 | } 71 | 72 | public void printAll() { 73 | for (int i = 0; i < cycles.size(); i++) { 74 | for (int j = 0; j < cycles.get(i).size(); j++) { 75 | System.out.print(cycles.get(i).get(j) + " -> "); 76 | } 77 | System.out.println(cycles.get(i).get(0)); 78 | System.out.println(); 79 | } 80 | 81 | } 82 | 83 | } 84 | 85 | public class Cycles { 86 | public static void main(String[] args) { 87 | Cycle c = new Cycle(); 88 | c.start(); 89 | c.printAll(); 90 | } 91 | } -------------------------------------------------------------------------------- /Searches/IterativeTernarySearch.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | import java.util.stream.Stream; 6 | 7 | import static java.lang.String.format; 8 | 9 | /** 10 | * A iterative version of a ternary search algorithm 11 | * This is better way to implement the ternary search, because a recursive version adds some overhead to a stack. 12 | * But in java the compile can transform the recursive version to iterative implicitly, 13 | * so there are no much differences between these two algorithms 14 | *

15 | * Worst-case performance Θ(log3(N)) 16 | * Best-case performance O(1) 17 | * Average performance Θ(log3(N)) 18 | * Worst-case space complexity O(1) 19 | * 20 | * @author Podshivalov Nikita (https://github.com/nikitap492) 21 | * @see SearchAlgorithm 22 | * @see TernarySearch 23 | * @since 2018-04-13 24 | */ 25 | 26 | public class IterativeTernarySearch implements SearchAlgorithm { 27 | 28 | 29 | @Override 30 | public > int find(T[] array, T key) { 31 | int left = 0; 32 | int right = array.length - 1; 33 | 34 | while (right > left) { 35 | 36 | int leftCmp = array[left].compareTo(key); 37 | int rightCmp = array[right].compareTo(key); 38 | if (leftCmp == 0) return left; 39 | if (rightCmp == 0) return right; 40 | 41 | int leftThird = left + (right - left) / 3 + 1; 42 | int rightThird = right - (right - left) / 3 - 1; 43 | 44 | 45 | if (array[leftThird].compareTo(key) <= 0) { 46 | left = leftThird; 47 | } else { 48 | right = rightThird; 49 | } 50 | } 51 | 52 | return -1; 53 | } 54 | 55 | 56 | public static void main(String[] args) { 57 | //just generate data 58 | Random r = new Random(); 59 | int size = 100; 60 | int maxElement = 100000; 61 | Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)) 62 | .limit(size) 63 | .sorted() 64 | .toArray(Integer[]::new); 65 | 66 | 67 | //the element that should be found 68 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 69 | 70 | IterativeTernarySearch search = new IterativeTernarySearch(); 71 | int atIndex = search.find(integers, shouldBeFound); 72 | 73 | System.out.println(format("Should be found: %d. Found %d at index %d. An array length %d", 74 | shouldBeFound, integers[atIndex], atIndex, size)); 75 | 76 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 77 | System.out.println(format("Found by system method at an index: %d. Is equal: %b", 78 | toCheck, toCheck == atIndex)); 79 | 80 | } 81 | 82 | 83 | } 84 | -------------------------------------------------------------------------------- /Others/Dijkshtra.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | import java.util.Stack; 6 | 7 | /** 8 | * @author Mayank K Jha 9 | */ 10 | 11 | public class Dijkshtra { 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | // n = Number of nodes or vertices 17 | int n = in.nextInt(); 18 | // m = Number of Edges 19 | int m = in.nextInt(); 20 | 21 | // Adjacency Matrix 22 | long[][] w = new long[n + 1][n + 1]; 23 | 24 | // Initializing Matrix with Certain Maximum Value for path b/w any two vertices 25 | for (long[] row : w) { 26 | Arrays.fill(row, 1000000L); 27 | } 28 | 29 | /* From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l 30 | For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l */ 31 | 32 | // Taking Input as Edge Location b/w a pair of vertices 33 | for (int i = 0; i < m; i++) { 34 | int x = in.nextInt(), y = in.nextInt(); 35 | long cmp = in.nextLong(); 36 | 37 | // Comparing previous edge value with current value - Cycle Case 38 | if (w[x][y] > cmp) { 39 | w[x][y] = cmp; 40 | w[y][x] = cmp; 41 | } 42 | } 43 | 44 | // Implementing Dijkshtra's Algorithm 45 | Stack t = new Stack<>(); 46 | int src = in.nextInt(); 47 | 48 | for (int i = 1; i <= n; i++) { 49 | if (i != src) { 50 | t.push(i); 51 | } 52 | } 53 | 54 | Stack p = new Stack<>(); 55 | p.push(src); 56 | w[src][src] = 0; 57 | 58 | while (!t.isEmpty()) { 59 | int min = 989997979; 60 | int loc = -1; 61 | 62 | for (int i = 0; i < t.size(); i++) { 63 | w[src][t.elementAt(i)] = Math.min(w[src][t.elementAt(i)], w[src][p.peek()] + w[p.peek()][t.elementAt(i)]); 64 | if (w[src][t.elementAt(i)] <= min) { 65 | min = (int) w[src][t.elementAt(i)]; 66 | loc = i; 67 | } 68 | } 69 | p.push(t.elementAt(loc)); 70 | t.removeElementAt(loc); 71 | } 72 | 73 | // Printing shortest path from the given source src 74 | for (int i = 1; i <= n; i++) { 75 | if (i != src && w[src][i] != 1000000L) { 76 | System.out.print(w[src][i] + " "); 77 | } 78 | // Printing -1 if there is no path b/w given pair of edges 79 | else if (i != src) { 80 | System.out.print("-1" + " "); 81 | } 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /Searches/IterativeBinarySearch.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | import java.util.stream.Stream; 6 | 7 | import static java.lang.String.format; 8 | 9 | /** 10 | * Binary search is one of the most popular algorithms 11 | * This class represents iterative version {@link BinarySearch} 12 | * Iterative binary search is likely to have lower constant factors because it doesn't involve the overhead of manipulating the call stack. 13 | * But in java the recursive version can be optimized by the compiler to this version. 14 | *

15 | * Worst-case performance O(log n) 16 | * Best-case performance O(1) 17 | * Average performance O(log n) 18 | * Worst-case space complexity O(1) 19 | * 20 | * @author Gabriele La Greca : https://github.com/thegabriele97 21 | * @author Podshivalov Nikita (https://github.com/nikitap492) 22 | * @see SearchAlgorithm 23 | * @see BinarySearch 24 | */ 25 | 26 | public final class IterativeBinarySearch implements SearchAlgorithm { 27 | 28 | /** 29 | * This method implements an iterative version of binary search algorithm 30 | * 31 | * @param array a sorted array 32 | * @param key the key to search in array 33 | * @return the index of key in the array or -1 if not found 34 | */ 35 | @Override 36 | public > int find(T[] array, T key) { 37 | int l, r, k, cmp; 38 | 39 | l = 0; 40 | r = array.length - 1; 41 | 42 | while (l <= r) { 43 | k = (l + r) / 2; 44 | cmp = key.compareTo(array[k]); 45 | 46 | if (cmp == 0) { 47 | return k; 48 | } else if (cmp < 0) { 49 | r = --k; 50 | } else { 51 | l = ++k; 52 | } 53 | } 54 | 55 | return -1; 56 | } 57 | 58 | //Only a main method for test purpose 59 | public static void main(String[] args) { 60 | Random r = new Random(); 61 | int size = 100; 62 | int maxElement = 100000; 63 | Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); 64 | 65 | 66 | //the element that should be found 67 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 68 | 69 | IterativeBinarySearch search = new IterativeBinarySearch(); 70 | int atIndex = search.find(integers, shouldBeFound); 71 | 72 | System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" 73 | , shouldBeFound, integers[atIndex], atIndex, size)); 74 | 75 | 76 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 77 | System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /DataStructures/Stacks/StackArrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | /** 4 | * This class implements a Stack using an ArrayList. 5 | *

6 | * A stack is exactly what it sounds like. An element gets added to the top of 7 | * the stack and only the element on the top may be removed. 8 | *

9 | * This is an ArrayList Implementation of a stack, where size is not 10 | * a problem we can extend the stack as much as we want. 11 | * 12 | * @author Unknown 13 | */ 14 | public class StackArrayList { 15 | 16 | /** 17 | * Main method 18 | * 19 | * @param args Command line arguments 20 | */ 21 | public static void main(String[] args) { 22 | 23 | StackArrayList myStackArrayList = new StackArrayList(); 24 | 25 | myStackArrayList.push(5); 26 | myStackArrayList.push(8); 27 | myStackArrayList.push(2); 28 | myStackArrayList.push(9); 29 | 30 | System.out.println("*********************Stack List Implementation*********************"); 31 | System.out.println(myStackArrayList.isEmpty()); // will print false 32 | System.out.println(myStackArrayList.peek()); // will print 9 33 | System.out.println(myStackArrayList.pop()); // will print 9 34 | System.out.println(myStackArrayList.peek()); // will print 2 35 | System.out.println(myStackArrayList.pop()); // will print 2 36 | } 37 | 38 | /** 39 | * ArrayList representation of the stack 40 | */ 41 | private ArrayList stackList; 42 | 43 | /** 44 | * Constructor 45 | */ 46 | public StackArrayList() { 47 | stackList = new ArrayList<>(); 48 | } 49 | 50 | /** 51 | * Adds value to the end of list which 52 | * is the top for stack 53 | * 54 | * @param value value to be added 55 | */ 56 | public void push(int value) { 57 | stackList.add(value); 58 | } 59 | 60 | /** 61 | * Pops last element of list which is indeed 62 | * the top for Stack 63 | * 64 | * @return Element popped 65 | */ 66 | public int pop() { 67 | 68 | if (!isEmpty()) { // checks for an empty Stack 69 | int popValue = stackList.get(stackList.size() - 1); 70 | stackList.remove(stackList.size() - 1); // removes the poped element from the list 71 | return popValue; 72 | } 73 | 74 | System.out.print("The stack is already empty!"); 75 | return -1; 76 | } 77 | 78 | /** 79 | * Checks for empty Stack 80 | * 81 | * @return true if stack is empty 82 | */ 83 | public boolean isEmpty() { 84 | return stackList.isEmpty(); 85 | } 86 | 87 | /** 88 | * Top element of stack 89 | * 90 | * @return top element of stack 91 | */ 92 | public int peek() { 93 | return stackList.get(stackList.size() - 1); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /ciphers/RSA.java: -------------------------------------------------------------------------------- 1 | package ciphers; 2 | 3 | import java.math.BigInteger; 4 | import java.security.SecureRandom; 5 | import javax.swing.JOptionPane; 6 | 7 | /** 8 | * @author Nguyen Duy Tiep on 23-Oct-17. 9 | */ 10 | public final class RSA { 11 | 12 | /** 13 | * Trivial test program. 14 | * 15 | * @param args 16 | * @deprecated TODO remove main and make JUnit Testing or any other 17 | * methodology 18 | */ 19 | public static void main(String[] args) { 20 | 21 | RSA rsa = new RSA(1024); 22 | String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :"); 23 | 24 | String ciphertext = rsa.encrypt(text1); 25 | JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext); 26 | 27 | JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext)); 28 | } 29 | 30 | private BigInteger modulus, privateKey, publicKey; 31 | 32 | /** 33 | * 34 | * @param bits 35 | */ 36 | public RSA(int bits) { 37 | generateKeys(bits); 38 | } 39 | 40 | /** 41 | * 42 | * @param message 43 | * @return encrypted message 44 | */ 45 | public synchronized String encrypt(String message) { 46 | return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); 47 | } 48 | 49 | /** 50 | * 51 | * @param message 52 | * @return encrypted message as big integer 53 | */ 54 | public synchronized BigInteger encrypt(BigInteger message) { 55 | return message.modPow(publicKey, modulus); 56 | } 57 | 58 | /** 59 | * 60 | * @param encryptedMessage 61 | * @return plain message 62 | */ 63 | public synchronized String decrypt(String encryptedMessage) { 64 | return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); 65 | } 66 | 67 | /** 68 | * 69 | * @param encryptedMessage 70 | * @return plain message as big integer 71 | */ 72 | public synchronized BigInteger decrypt(BigInteger encryptedMessage) { 73 | return encryptedMessage.modPow(privateKey, modulus); 74 | } 75 | 76 | /** 77 | * Generate a new public and private key set. 78 | * 79 | * @param bits 80 | */ 81 | public synchronized void generateKeys(int bits) { 82 | SecureRandom r = new SecureRandom(); 83 | BigInteger p = new BigInteger(bits / 2, 100, r); 84 | BigInteger q = new BigInteger(bits / 2, 100, r); 85 | modulus = p.multiply(q); 86 | 87 | BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); 88 | 89 | publicKey = new BigInteger("3"); 90 | 91 | while (m.gcd(publicKey).intValue() > 1) { 92 | publicKey = publicKey.add(new BigInteger("2")); 93 | } 94 | 95 | privateKey = publicKey.modInverse(m); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /DynamicProgramming/CoinChange.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | */ 6 | public class CoinChange { 7 | 8 | // Driver Program 9 | public static void main(String[] args) { 10 | 11 | int amount = 12; 12 | int[] coins = {2, 4, 5}; 13 | 14 | System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount)); 15 | System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount)); 16 | 17 | } 18 | 19 | /** 20 | * This method finds the number of combinations of getting change for a given amount and change coins 21 | * 22 | * @param coins The list of coins 23 | * @param amount The amount for which we need to find the change 24 | * Finds the number of combinations of change 25 | **/ 26 | public static int change(int[] coins, int amount) { 27 | 28 | int[] combinations = new int[amount + 1]; 29 | combinations[0] = 1; 30 | 31 | for (int coin : coins) { 32 | for (int i = coin; i < amount + 1; i++) { 33 | combinations[i] += combinations[i - coin]; 34 | } 35 | // Uncomment the below line to see the state of combinations for each coin 36 | // printAmount(combinations); 37 | } 38 | 39 | return combinations[amount]; 40 | } 41 | 42 | /** 43 | * This method finds the minimum number of coins needed for a given amount. 44 | * 45 | * @param coins The list of coins 46 | * @param amount The amount for which we need to find the minimum number of coins. 47 | * Finds the the minimum number of coins that make a given value. 48 | **/ 49 | public static int minimumCoins(int[] coins, int amount) { 50 | //minimumCoins[i] will store the minimum coins needed for amount i 51 | int[] minimumCoins = new int[amount + 1]; 52 | 53 | minimumCoins[0] = 0; 54 | 55 | for (int i = 1; i <= amount; i++) { 56 | minimumCoins[i] = Integer.MAX_VALUE; 57 | } 58 | for (int i = 1; i <= amount; i++) { 59 | for (int coin : coins) { 60 | if (coin <= i) { 61 | int sub_res = minimumCoins[i - coin]; 62 | if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) 63 | minimumCoins[i] = sub_res + 1; 64 | } 65 | } 66 | } 67 | // Uncomment the below line to see the state of combinations for each coin 68 | //printAmount(minimumCoins); 69 | return minimumCoins[amount]; 70 | } 71 | 72 | // A basic print method which prints all the contents of the array 73 | public static void printAmount(int[] arr) { 74 | for (int i = 0; i < arr.length; i++) { 75 | System.out.print(arr[i] + " "); 76 | } 77 | System.out.println(); 78 | } 79 | } -------------------------------------------------------------------------------- /DataStructures/Stacks/BalancedBrackets.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Stacks; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * The nested brackets problem is a problem that determines if a sequence of 7 | * brackets are properly nested. A sequence of brackets s is considered properly 8 | * nested if any of the following conditions are true: - s is empty - s has the 9 | * form (U) or [U] or {U} where U is a properly nested string - s has the form 10 | * VW where V and W are properly nested strings For example, the string 11 | * "()()[()]" is properly nested but "[(()]" is not. The function called 12 | * is_balanced takes as input a string S which is a sequence of brackets and 13 | * returns true if S is nested and false otherwise. 14 | * 15 | * @author akshay sharma 16 | * @author khalil2535 17 | * @author shellhub 18 | */ 19 | class BalancedBrackets { 20 | 21 | /** 22 | * Check if {@code leftBracket} and {@code rightBracket} is paired or not 23 | * 24 | * @param leftBracket left bracket 25 | * @param rightBracket right bracket 26 | * @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired, 27 | * otherwise {@code false} 28 | */ 29 | public static boolean isPaired(char leftBracket, char rightBracket) { 30 | char[][] pairedBrackets = { 31 | {'(', ')'}, 32 | {'[', ']'}, 33 | {'{', '}'}, 34 | {'<', '>'} 35 | }; 36 | for (char[] pairedBracket : pairedBrackets) { 37 | if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { 38 | return true; 39 | } 40 | } 41 | return false; 42 | } 43 | 44 | /** 45 | * Check if {@code brackets} is balanced 46 | * 47 | * @param brackets the brackets 48 | * @return {@code true} if {@code brackets} is balanced, otherwise {@code false} 49 | */ 50 | public static boolean isBalanced(String brackets) { 51 | if (brackets == null) { 52 | throw new IllegalArgumentException("brackets is null"); 53 | } 54 | Stack bracketsStack = new Stack<>(); 55 | for (char bracket : brackets.toCharArray()) { 56 | switch (bracket) { 57 | case '(': 58 | case '[': 59 | case '{': 60 | bracketsStack.push(bracket); 61 | break; 62 | case ')': 63 | case ']': 64 | case '}': 65 | if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { 66 | return false; 67 | } 68 | break; 69 | default: /* other character is invalid */ 70 | return false; 71 | } 72 | } 73 | return bracketsStack.isEmpty(); 74 | } 75 | 76 | 77 | public static void main(String[] args) { 78 | assert isBalanced("[()]{}{[()()]()}"); 79 | assert !isBalanced("[(])"); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /DynamicProgramming/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | /** 8 | * @author Varun Upadhyay (https://github.com/varunu28) 9 | */ 10 | 11 | public class Fibonacci { 12 | 13 | private static Map map = new HashMap<>(); 14 | 15 | 16 | public static void main(String[] args) { 17 | 18 | // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] 19 | Scanner sc = new Scanner(System.in); 20 | int n = sc.nextInt(); 21 | 22 | System.out.println(fibMemo(n)); 23 | System.out.println(fibBotUp(n)); 24 | System.out.println(fibOptimized(n)); 25 | } 26 | 27 | /** 28 | * This method finds the nth fibonacci number using memoization technique 29 | * 30 | * @param n The input n for which we have to determine the fibonacci number 31 | * Outputs the nth fibonacci number 32 | **/ 33 | public static int fibMemo(int n) { 34 | if (map.containsKey(n)) { 35 | return map.get(n); 36 | } 37 | 38 | int f; 39 | 40 | if (n <= 1) { 41 | f = n; 42 | } else { 43 | f = fibMemo(n - 1) + fibMemo(n - 2); 44 | map.put(n, f); 45 | } 46 | return f; 47 | } 48 | 49 | /** 50 | * This method finds the nth fibonacci number using bottom up 51 | * 52 | * @param n The input n for which we have to determine the fibonacci number 53 | * Outputs the nth fibonacci number 54 | **/ 55 | public static int fibBotUp(int n) { 56 | 57 | Map fib = new HashMap<>(); 58 | 59 | for (int i = 0; i <= n; i++) { 60 | int f; 61 | if (i <= 1) { 62 | f = i; 63 | } else { 64 | f = fib.get(i - 1) + fib.get(i - 2); 65 | } 66 | fib.put(i, f); 67 | } 68 | 69 | return fib.get(n); 70 | } 71 | 72 | 73 | /** 74 | * This method finds the nth fibonacci number using bottom up 75 | * 76 | * @param n The input n for which we have to determine the fibonacci number 77 | * Outputs the nth fibonacci number 78 | *

79 | * This is optimized version of Fibonacci Program. Without using Hashmap and recursion. 80 | * It saves both memory and time. 81 | * Space Complexity will be O(1) 82 | * Time Complexity will be O(n) 83 | *

84 | * Whereas , the above functions will take O(n) Space. 85 | * @author Shoaib Rayeen (https://github.com/shoaibrayeen) 86 | **/ 87 | public static int fibOptimized(int n) { 88 | if (n == 0) { 89 | return 0; 90 | } 91 | int prev = 0, res = 1, next; 92 | for (int i = 2; i <= n; i++) { 93 | next = prev + res; 94 | prev = res; 95 | res = next; 96 | } 97 | return res; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Searches/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package Searches; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | import java.util.concurrent.ThreadLocalRandom; 6 | import java.util.stream.IntStream; 7 | 8 | import static java.lang.String.format; 9 | 10 | /** 11 | * 12 | * 13 | * 14 | * Binary search is one of the most popular algorithms 15 | * The algorithm finds the position of a target value within a sorted array 16 | * 17 | * Worst-case performance O(log n) 18 | * Best-case performance O(1) 19 | * Average performance O(log n) 20 | * Worst-case space complexity O(1) 21 | * 22 | * 23 | * @author Varun Upadhyay (https://github.com/varunu28) 24 | * @author Podshivalov Nikita (https://github.com/nikitap492) 25 | * 26 | * @see SearchAlgorithm 27 | * @see IterativeBinarySearch 28 | * 29 | */ 30 | 31 | class BinarySearch implements SearchAlgorithm { 32 | 33 | /** 34 | * 35 | * @param array is an array where the element should be found 36 | * @param key is an element which should be found 37 | * @param is any comparable type 38 | * @return index of the element 39 | */ 40 | @Override 41 | public > int find(T[] array, T key) { 42 | return search(array, key, 0, array.length); 43 | } 44 | 45 | /** 46 | * This method implements the Generic Binary Search 47 | * 48 | * @param array The array to make the binary search 49 | * @param key The number you are looking for 50 | * @param left The lower bound 51 | * @param right The upper bound 52 | * @return the location of the key 53 | **/ 54 | private > int search(T array[], T key, int left, int right){ 55 | if (right < left) return -1; // this means that the key not found 56 | 57 | // find median 58 | int median = (left + right) >>> 1; 59 | int comp = key.compareTo(array[median]); 60 | 61 | if (comp == 0) { 62 | return median; 63 | } else if (comp < 0) { 64 | return search(array, key, left, median - 1); 65 | } else { 66 | return search(array, key, median + 1, right); 67 | } 68 | } 69 | 70 | // Driver Program 71 | public static void main(String[] args) { 72 | // Just generate data 73 | Random r = ThreadLocalRandom.current(); 74 | 75 | int size = 100; 76 | int maxElement = 100000; 77 | 78 | Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[]::new); 79 | 80 | 81 | // The element that should be found 82 | int shouldBeFound = integers[r.nextInt(size - 1)]; 83 | 84 | BinarySearch search = new BinarySearch(); 85 | int atIndex = search.find(integers, shouldBeFound); 86 | 87 | System.out.println(format( 88 | "Should be found: %d. Found %d at index %d. An array length %d", 89 | shouldBeFound, integers[atIndex], atIndex, size 90 | )); 91 | 92 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 93 | System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /DataStructures/Trees/PrintTopViewofTree.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Trees;// Java program to print top view of Binary tree 2 | 3 | import java.util.HashSet; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | 7 | // Class for a tree node 8 | class TreeNode { 9 | // Members 10 | int key; 11 | TreeNode left, right; 12 | 13 | // Constructor 14 | public TreeNode(int key) { 15 | this.key = key; 16 | left = right = null; 17 | } 18 | } 19 | 20 | // A class to represent a queue item. The queue is used to do Level 21 | // order traversal. Every Queue item contains node and horizontal 22 | // distance of node from root 23 | class QItem { 24 | TreeNode node; 25 | int hd; 26 | 27 | public QItem(TreeNode n, int h) { 28 | node = n; 29 | hd = h; 30 | } 31 | } 32 | 33 | // Class for a Binary Tree 34 | class Tree { 35 | TreeNode root; 36 | 37 | // Constructors 38 | public Tree() { 39 | root = null; 40 | } 41 | 42 | public Tree(TreeNode n) { 43 | root = n; 44 | } 45 | 46 | // This method prints nodes in top view of binary tree 47 | public void printTopView() { 48 | // base case 49 | if (root == null) { 50 | return; 51 | } 52 | 53 | // Creates an empty hashset 54 | HashSet set = new HashSet<>(); 55 | 56 | // Create a queue and add root to it 57 | Queue Q = new LinkedList(); 58 | Q.add(new QItem(root, 0)); // Horizontal distance of root is 0 59 | 60 | // Standard BFS or level order traversal loop 61 | while (!Q.isEmpty()) { 62 | // Remove the front item and get its details 63 | QItem qi = Q.remove(); 64 | int hd = qi.hd; 65 | TreeNode n = qi.node; 66 | 67 | // If this is the first node at its horizontal distance, 68 | // then this node is in top view 69 | if (!set.contains(hd)) { 70 | set.add(hd); 71 | System.out.print(n.key + " "); 72 | } 73 | 74 | // Enqueue left and right children of current node 75 | if (n.left != null) 76 | Q.add(new QItem(n.left, hd - 1)); 77 | if (n.right != null) 78 | Q.add(new QItem(n.right, hd + 1)); 79 | } 80 | } 81 | } 82 | 83 | // Driver class to test above methods 84 | public class PrintTopViewofTree { 85 | public static void main(String[] args) { 86 | /* Create following Binary Tree 87 | 1 88 | / \ 89 | 2 3 90 | \ 91 | 4 92 | \ 93 | 5 94 | \ 95 | 6*/ 96 | TreeNode root = new TreeNode(1); 97 | root.left = new TreeNode(2); 98 | root.right = new TreeNode(3); 99 | root.left.right = new TreeNode(4); 100 | root.left.right.right = new TreeNode(5); 101 | root.left.right.right.right = new TreeNode(6); 102 | Tree t = new Tree(root); 103 | System.out.println("Following are nodes in top view of Binary Tree"); 104 | t.printTopView(); 105 | } 106 | } -------------------------------------------------------------------------------- /DynamicProgramming/EditDistance.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | /** 4 | * A DynamicProgramming based solution for Edit Distance problem In Java 5 | * Description of Edit Distance with an Example: 6 | *

7 | * Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another, 8 | * by counting the minimum number of operations required to transform one string into the other. The 9 | * distance operations are the removal, insertion, or substitution of a character in the string. 10 | *

11 | *

12 | * The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is: 13 | *

14 | * kitten → sitten (substitution of "s" for "k") 15 | * sitten → sittin (substitution of "i" for "e") 16 | * sittin → sitting (insertion of "g" at the end). 17 | * 18 | * @author SUBHAM SANGHAI 19 | **/ 20 | 21 | import java.util.Scanner; 22 | 23 | public class EditDistance { 24 | 25 | public static int minDistance(String word1, String word2) { 26 | int len1 = word1.length(); 27 | int len2 = word2.length(); 28 | // len1+1, len2+1, because finally return dp[len1][len2] 29 | int[][] dp = new int[len1 + 1][len2 + 1]; 30 | /* If second string is empty, the only option is to 31 | insert all characters of first string into second*/ 32 | for (int i = 0; i <= len1; i++) { 33 | dp[i][0] = i; 34 | } 35 | /* If first string is empty, the only option is to 36 | insert all characters of second string into first*/ 37 | for (int j = 0; j <= len2; j++) { 38 | dp[0][j] = j; 39 | } 40 | //iterate though, and check last char 41 | for (int i = 0; i < len1; i++) { 42 | char c1 = word1.charAt(i); 43 | for (int j = 0; j < len2; j++) { 44 | char c2 = word2.charAt(j); 45 | //if last two chars equal 46 | if (c1 == c2) { 47 | //update dp value for +1 length 48 | dp[i + 1][j + 1] = dp[i][j]; 49 | } else { 50 | /* if two characters are different , 51 | then take the minimum of the various operations(i.e insertion,removal,substitution)*/ 52 | int replace = dp[i][j] + 1; 53 | int insert = dp[i][j + 1] + 1; 54 | int delete = dp[i + 1][j] + 1; 55 | 56 | int min = replace > insert ? insert : replace; 57 | min = delete > min ? min : delete; 58 | dp[i + 1][j + 1] = min; 59 | } 60 | } 61 | } 62 | /* return the final answer , after traversing through both the strings*/ 63 | return dp[len1][len2]; 64 | } 65 | 66 | 67 | public static void main(String[] args) { 68 | Scanner input = new Scanner(System.in); 69 | String s1, s2; 70 | System.out.println("Enter the First String"); 71 | s1 = input.nextLine(); 72 | System.out.println("Enter the Second String"); 73 | s2 = input.nextLine(); 74 | //ans stores the final Edit Distance between the two strings 75 | int ans = minDistance(s1, s2); 76 | System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Sorts/MergeSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.print; 4 | 5 | /** 6 | * This method implements the Generic Merge Sort 7 | * 8 | * @author Varun Upadhyay (https://github.com/varunu28) 9 | * @author Podshivalov Nikita (https://github.com/nikitap492) 10 | * @see SortAlgorithm 11 | */ 12 | 13 | class MergeSort implements SortAlgorithm { 14 | 15 | /** 16 | * This method implements the Generic Merge Sort 17 | * 18 | * @param unsorted the array which should be sorted 19 | * @param Comparable class 20 | * @return sorted array 21 | */ 22 | @Override 23 | @SuppressWarnings("unchecked") 24 | public > T[] sort(T[] unsorted) { 25 | T[] tmp = (T[]) new Comparable[unsorted.length]; 26 | doSort(unsorted, tmp, 0, unsorted.length - 1); 27 | return unsorted; 28 | } 29 | 30 | /** 31 | * @param arr The array to be sorted 32 | * @param temp The copy of the actual array 33 | * @param left The first index of the array 34 | * @param right The last index of the array 35 | * Recursively sorts the array in increasing order 36 | **/ 37 | private static > void doSort(T[] arr, T[] temp, int left, int right) { 38 | if (left < right) { 39 | int mid = left + (right - left) / 2; 40 | doSort(arr, temp, left, mid); 41 | doSort(arr, temp, mid + 1, right); 42 | merge(arr, temp, left, mid, right); 43 | } 44 | 45 | } 46 | 47 | /** 48 | * This method implements the merge step of the merge sort 49 | * 50 | * @param arr The array to be sorted 51 | * @param temp The copy of the actual array 52 | * @param left The first index of the array 53 | * @param mid The middle index of the array 54 | * @param right The last index of the array 55 | * merges two parts of an array in increasing order 56 | **/ 57 | 58 | private static > void merge(T[] arr, T[] temp, int left, int mid, int right) { 59 | System.arraycopy(arr, left, temp, left, right - left + 1); 60 | 61 | 62 | int i = left; 63 | int j = mid + 1; 64 | int k = left; 65 | 66 | while (i <= mid && j <= right) { 67 | if (temp[i].compareTo(temp[j]) <= 0) { 68 | arr[k++] = temp[i++]; 69 | } else { 70 | arr[k++] = temp[j++]; 71 | } 72 | } 73 | 74 | while (i <= mid) { 75 | arr[k++] = temp[i++]; 76 | } 77 | 78 | while (j <= right) { 79 | arr[k++] = temp[j++]; 80 | } 81 | } 82 | 83 | // Driver program 84 | public static void main(String[] args) { 85 | 86 | // Integer Input 87 | Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 88 | MergeSort mergeSort = new MergeSort(); 89 | mergeSort.sort(arr); 90 | 91 | // Output => 1 4 6 9 12 23 54 78 231 92 | print(arr); 93 | 94 | // String Inpu 95 | String[] stringArray = {"c", "a", "e", "b", "d"}; 96 | mergeSort.sort(stringArray); 97 | //Output => a b c d e 98 | print(stringArray); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Others/TopKWords.java: -------------------------------------------------------------------------------- 1 | package Others; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | /* display the most frequent K words in the file and the times it appear 7 | in the file – shown in order (ignore case and periods) */ 8 | 9 | public class TopKWords { 10 | static class CountWords { 11 | private String fileName; 12 | 13 | public CountWords(String fileName) { 14 | this.fileName = fileName; 15 | } 16 | 17 | public Map getDictionary() { 18 | Map dictionary = new HashMap<>(); 19 | FileInputStream fis = null; 20 | 21 | try { 22 | 23 | fis = new FileInputStream(fileName); // open the file 24 | int in = 0; 25 | String s = ""; // init a empty word 26 | in = fis.read(); // read one character 27 | 28 | while (-1 != in) { 29 | if (Character.isLetter((char) in)) { 30 | s += (char) in; //if get a letter, append to s 31 | } else { 32 | // this branch means an entire word has just been read 33 | if (s.length() > 0) { 34 | // see whether word exists or not 35 | if (dictionary.containsKey(s)) { 36 | // if exist, count++ 37 | dictionary.put(s, dictionary.get(s) + 1); 38 | } else { 39 | // if not exist, initiate count of this word with 1 40 | dictionary.put(s, 1); 41 | } 42 | } 43 | s = ""; // reInit a empty word 44 | } 45 | in = fis.read(); 46 | } 47 | return dictionary; 48 | } catch (IOException e) { 49 | e.printStackTrace(); 50 | } finally { 51 | try { 52 | // you always have to close the I/O streams 53 | fis.close(); 54 | } catch (IOException e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | return null; 59 | } 60 | } 61 | 62 | public static void main(String[] args) { 63 | // you can replace the filePath with yours 64 | CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt"); 65 | Map dictionary = cw.getDictionary(); // get the words dictionary: {word: frequency} 66 | 67 | // we change the map to list for convenient sort 68 | List> list = new ArrayList<>(dictionary.entrySet()); 69 | 70 | // sort by lambda valueComparator 71 | list.sort(Comparator.comparing( 72 | m -> m.getValue()) 73 | ); 74 | 75 | Scanner input = new Scanner(System.in); 76 | int k = input.nextInt(); 77 | while (k > list.size()) { 78 | System.out.println("Retype a number, your number is too large"); 79 | input = new Scanner(System.in); 80 | k = input.nextInt(); 81 | } 82 | for (int i = 0; i < k; i++) { 83 | System.out.println(list.get(list.size() - i - 1)); 84 | } 85 | } 86 | } 87 | 88 | -------------------------------------------------------------------------------- /Sorts/QuickSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import static Sorts.SortUtils.*; 4 | 5 | /** 6 | * @author Varun Upadhyay (https://github.com/varunu28) 7 | * @author Podshivalov Nikita (https://github.com/nikitap492) 8 | * @see SortAlgorithm 9 | */ 10 | class QuickSort implements SortAlgorithm { 11 | 12 | /** 13 | * This method implements the Generic Quick Sort 14 | * 15 | * @param array The array to be sorted 16 | * Sorts the array in increasing order 17 | **/ 18 | 19 | @Override 20 | public > T[] sort(T[] array) { 21 | doSort(array, 0, array.length - 1); 22 | return array; 23 | } 24 | 25 | 26 | /** 27 | * The sorting process 28 | * 29 | * @param left The first index of an array 30 | * @param right The last index of an array 31 | * @param array The array to be sorted 32 | **/ 33 | 34 | private static > void doSort(T[] array, int left, int right) { 35 | if (left < right) { 36 | int pivot = randomPartition(array, left, right); 37 | doSort(array, left, pivot - 1); 38 | doSort(array, pivot, right); 39 | } 40 | } 41 | 42 | /** 43 | * Ramdomize the array to avoid the basically ordered sequences 44 | * 45 | * @param array The array to be sorted 46 | * @param left The first index of an array 47 | * @param right The last index of an array 48 | * @return the partition index of the array 49 | */ 50 | 51 | private static > int randomPartition(T[] array, int left, int right) { 52 | int randomIndex = left + (int)(Math.random()*(right - left + 1)); 53 | swap(array, randomIndex, right); 54 | return partition(array, left, right); 55 | } 56 | 57 | /** 58 | * This method finds the partition index for an array 59 | * 60 | * @param array The array to be sorted 61 | * @param left The first index of an array 62 | * @param right The last index of an array 63 | * Finds the partition index of an array 64 | **/ 65 | 66 | private static > int partition(T[] array, int left, int right) { 67 | int mid = (left + right) / 2; 68 | T pivot = array[mid]; 69 | 70 | while (left <= right) { 71 | while (less(array[left], pivot)) { 72 | ++left; 73 | } 74 | while (less(pivot, array[right])) { 75 | --right; 76 | } 77 | if (left <= right) { 78 | swap(array, left, right); 79 | ++left; 80 | --right; 81 | } 82 | } 83 | return left; 84 | } 85 | 86 | // Driver Program 87 | public static void main(String[] args) { 88 | 89 | // For integer input 90 | Integer[] array = {3, 4, 1, 32, 0, 1, 5, 12, 2, 5, 7, 8, 9, 2, 44, 111, 5}; 91 | 92 | QuickSort quickSort = new QuickSort(); 93 | quickSort.sort(array); 94 | 95 | //Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111 96 | print(array); 97 | 98 | String[] stringArray = {"c", "a", "e", "b", "d"}; 99 | quickSort.sort(stringArray); 100 | 101 | //Output => a b c d e 102 | print(stringArray); 103 | } 104 | } 105 | 106 | -------------------------------------------------------------------------------- /Sorts/CountingSort.java: -------------------------------------------------------------------------------- 1 | package Sorts; 2 | 3 | import java.util.*; 4 | import java.util.stream.IntStream; 5 | import java.util.stream.Stream; 6 | 7 | import static java.util.stream.Collectors.toList; 8 | import static java.util.stream.Collectors.toMap; 9 | import static Sorts.SortUtils.print; 10 | 11 | /** 12 | * @author Youssef Ali (https://github.com/youssefAli11997) 13 | * @author Podshivalov Nikita (https://github.com/nikitap492) 14 | */ 15 | class CountingSort implements SortAlgorithm { 16 | 17 | @Override 18 | public > T[] sort(T[] unsorted) { 19 | return sort(Arrays.asList(unsorted)).toArray(unsorted); 20 | } 21 | 22 | /** 23 | * This method implements the Generic Counting Sort 24 | * 25 | * @param list The list to be sorted 26 | *

27 | * Sorts the list in increasing order 28 | * The method uses list elements as keys in the frequency map 29 | **/ 30 | @Override 31 | public > List sort(List list) { 32 | 33 | Map frequency = new TreeMap<>(); 34 | // The final output array 35 | List sortedArray = new ArrayList<>(list.size()); 36 | 37 | // Counting the frequency of @param array elements 38 | list.forEach(v -> frequency.put(v, frequency.getOrDefault(v, 0) + 1)); 39 | 40 | // Filling the sortedArray 41 | for (Map.Entry element : frequency.entrySet()) { 42 | for (int j = 0; j < element.getValue(); j++) { 43 | sortedArray.add(element.getKey()); 44 | } 45 | } 46 | 47 | return sortedArray; 48 | } 49 | 50 | 51 | /** 52 | * Stream Counting Sort 53 | * The same as method {@link CountingSort#sort(List)} } but this method uses stream API 54 | * 55 | * @param list The list to be sorted 56 | **/ 57 | private static > List streamSort(List list) { 58 | return list.stream() 59 | .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)) 60 | .entrySet() 61 | .stream() 62 | .flatMap(entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey())) 63 | .collect(toList()); 64 | } 65 | 66 | // Driver Program 67 | public static void main(String[] args) { 68 | // Integer Input 69 | List unsortedInts = Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList()); 70 | CountingSort countingSort = new CountingSort(); 71 | 72 | System.out.println("Before Sorting:"); 73 | print(unsortedInts); 74 | 75 | // Output => 1 1 4 6 9 9 12 23 23 54 78 231 76 | System.out.println("After Sorting:"); 77 | print(countingSort.sort(unsortedInts)); 78 | System.out.println("After Sorting By Streams:"); 79 | print(streamSort(unsortedInts)); 80 | 81 | System.out.println("\n------------------------------\n"); 82 | 83 | // String Input 84 | List unsortedStrings = Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList()); 85 | 86 | System.out.println("Before Sorting:"); 87 | print(unsortedStrings); 88 | 89 | //Output => a a b c c d e f g 90 | System.out.println("After Sorting:"); 91 | print(countingSort.sort(unsortedStrings)); 92 | 93 | System.out.println("After Sorting By Streams:"); 94 | print(streamSort(unsortedStrings)); 95 | 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /DataStructures/Graphs/FloydWarshall.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Graphs; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class FloydWarshall { 7 | private int DistanceMatrix[][]; 8 | private int numberofvertices;//number of vertices in the graph 9 | public static final int INFINITY = 999; 10 | 11 | public FloydWarshall(int numberofvertices) { 12 | DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1];//stores the value of distance from all the possible path form the source vertex to destination vertex 13 | Arrays.fill(DistanceMatrix, 0); 14 | this.numberofvertices = numberofvertices; 15 | } 16 | 17 | public void floydwarshall(int AdjacencyMatrix[][])//calculates all the distances from source to destination vertex 18 | { 19 | for (int source = 1; source <= numberofvertices; source++) { 20 | for (int destination = 1; destination <= numberofvertices; destination++) { 21 | DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; 22 | } 23 | } 24 | for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) { 25 | for (int source = 1; source <= numberofvertices; source++) { 26 | for (int destination = 1; destination <= numberofvertices; destination++) { 27 | if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] 28 | < DistanceMatrix[source][destination]) 29 | // if the new distance calculated is less then the earlier shortest 30 | // calculated distance it get replaced as new shortest distance 31 | { 32 | DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] 33 | + DistanceMatrix[intermediate][destination]; 34 | } 35 | } 36 | } 37 | } 38 | for (int source = 1; source <= numberofvertices; source++) 39 | System.out.print("\t" + source); 40 | System.out.println(); 41 | for (int source = 1; source <= numberofvertices; source++) { 42 | System.out.print(source + "\t"); 43 | for (int destination = 1; destination <= numberofvertices; destination++) { 44 | System.out.print(DistanceMatrix[source][destination] + "\t"); 45 | } 46 | System.out.println(); 47 | } 48 | } 49 | 50 | public static void main(String... arg) { 51 | Scanner scan = new Scanner(System.in); 52 | System.out.println("Enter the number of vertices"); 53 | int numberOfVertices = scan.nextInt(); 54 | int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1]; 55 | System.out.println("Enter the Weighted Matrix for the graph"); 56 | for (int source = 1; source <= numberOfVertices; source++) { 57 | for (int destination = 1; destination <= numberOfVertices; destination++) { 58 | adjacencyMatrix[source][destination] = scan.nextInt(); 59 | if (source == destination) { 60 | adjacencyMatrix[source][destination] = 0; 61 | continue; 62 | } 63 | if (adjacencyMatrix[source][destination] == 0) { 64 | adjacencyMatrix[source][destination] = INFINITY; 65 | } 66 | } 67 | } 68 | System.out.println("The Transitive Closure of the Graph"); 69 | FloydWarshall floydwarshall = new FloydWarshall(numberOfVertices); 70 | floydwarshall.floydwarshall(adjacencyMatrix); 71 | scan.close(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /DataStructures/Stacks/StackOfLinkedList.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Stacks; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | */ 6 | 7 | // An implementation of a Stack using a Linked List 8 | 9 | class StackOfLinkedList { 10 | 11 | public static void main(String[] args) { 12 | 13 | LinkedListStack stack = new LinkedListStack(); 14 | stack.push(1); 15 | stack.push(2); 16 | stack.push(3); 17 | stack.push(4); 18 | stack.push(5); 19 | 20 | System.out.println(stack); 21 | 22 | System.out.println("Size of stack currently is: " + stack.getSize()); 23 | 24 | assert stack.pop() == 5; 25 | assert stack.pop() == 4; 26 | 27 | System.out.println("Top element of stack currently is: " + stack.peek()); 28 | } 29 | } 30 | 31 | // A node class 32 | 33 | class Node { 34 | public int data; 35 | public Node next; 36 | 37 | public Node(int data) { 38 | this.data = data; 39 | this.next = null; 40 | } 41 | } 42 | 43 | /** 44 | * A class which implements a stack using a linked list 45 | *

46 | * Contains all the stack methods : push, pop, printStack, isEmpty 47 | **/ 48 | 49 | class LinkedListStack { 50 | 51 | /** 52 | * Top of stack 53 | */ 54 | Node head; 55 | 56 | /** 57 | * Size of stack 58 | */ 59 | private int size; 60 | 61 | /** 62 | * Init properties 63 | */ 64 | public LinkedListStack() { 65 | head = null; 66 | size = 0; 67 | } 68 | 69 | /** 70 | * Add element at top 71 | * 72 | * @param x to be added 73 | * @return true if add successfully 74 | */ 75 | public boolean push(int x) { 76 | Node newNode = new Node(x); 77 | newNode.next = head; 78 | head = newNode; 79 | size++; 80 | return true; 81 | } 82 | 83 | /** 84 | * Pop element at top of stack 85 | * 86 | * @return element at top of stack 87 | * @throws NoSuchElementException if stack is empty 88 | */ 89 | public int pop() { 90 | if (size == 0) { 91 | throw new NoSuchElementException("Empty stack. Nothing to pop"); 92 | } 93 | Node destroy = head; 94 | head = head.next; 95 | int retValue = destroy.data; 96 | destroy = null; // clear to let GC do it's work 97 | size--; 98 | return retValue; 99 | } 100 | 101 | /** 102 | * Peek element at top of stack 103 | * 104 | * @return element at top of stack 105 | * @throws NoSuchElementException if stack is empty 106 | */ 107 | public int peek() { 108 | if (size == 0) { 109 | throw new NoSuchElementException("Empty stack. Nothing to pop"); 110 | } 111 | return head.data; 112 | } 113 | 114 | @Override 115 | public String toString() { 116 | Node cur = head; 117 | StringBuilder builder = new StringBuilder(); 118 | while (cur != null) { 119 | builder.append(cur.data).append("->"); 120 | cur = cur.next; 121 | } 122 | return builder.replace(builder.length() - 2, builder.length(), "").toString(); 123 | } 124 | 125 | /** 126 | * Check if stack is empty 127 | * 128 | * @return true if stack is empty, otherwise false 129 | */ 130 | public boolean isEmpty() { 131 | return size == 0; 132 | } 133 | 134 | /** 135 | * Return size of stack 136 | * 137 | * @return size of stack 138 | */ 139 | public int getSize() { 140 | return size; 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /DataStructures/Trees/TreeTraversal.java: -------------------------------------------------------------------------------- 1 | package DataStructures.Trees; 2 | 3 | import java.util.LinkedList; 4 | 5 | /** 6 | * @author Varun Upadhyay (https://github.com/varunu28) 7 | */ 8 | 9 | 10 | // Driver Program 11 | public class TreeTraversal { 12 | public static void main(String[] args) { 13 | Node tree = new Node(5); 14 | tree.insert(3); 15 | tree.insert(2); 16 | tree.insert(7); 17 | tree.insert(4); 18 | tree.insert(6); 19 | tree.insert(8); 20 | 21 | // Prints 5 3 2 4 7 6 8 22 | System.out.println("Pre order traversal:"); 23 | tree.printPreOrder(); 24 | System.out.println(); 25 | // Prints 2 3 4 5 6 7 8 26 | System.out.println("In order traversal:"); 27 | tree.printInOrder(); 28 | System.out.println(); 29 | // Prints 2 4 3 6 8 7 5 30 | System.out.println("Post order traversal:"); 31 | tree.printPostOrder(); 32 | System.out.println(); 33 | // Prints 5 3 7 2 4 6 8 34 | System.out.println("Level order traversal:"); 35 | tree.printLevelOrder(); 36 | System.out.println(); 37 | } 38 | } 39 | 40 | /** 41 | * The Node class which initializes a Node of a tree 42 | * Consists of all 4 traversal methods: printInOrder, printPostOrder, printPreOrder & printLevelOrder 43 | * printInOrder: LEFT -> ROOT -> RIGHT 44 | * printPreOrder: ROOT -> LEFT -> RIGHT 45 | * printPostOrder: LEFT -> RIGHT -> ROOT 46 | * printLevelOrder: Prints by level (starting at root), from left to right. 47 | */ 48 | class Node { 49 | Node left, right; 50 | int data; 51 | 52 | public Node(int data) { 53 | this.data = data; 54 | } 55 | 56 | public void insert(int value) { 57 | if (value < data) { 58 | if (left == null) { 59 | left = new Node(value); 60 | } else { 61 | left.insert(value); 62 | } 63 | } else { 64 | if (right == null) { 65 | right = new Node(value); 66 | } else { 67 | right.insert(value); 68 | } 69 | } 70 | } 71 | 72 | public void printInOrder() { 73 | if (left != null) { 74 | left.printInOrder(); 75 | } 76 | System.out.print(data + " "); 77 | if (right != null) { 78 | right.printInOrder(); 79 | } 80 | } 81 | 82 | public void printPreOrder() { 83 | System.out.print(data + " "); 84 | if (left != null) { 85 | left.printPreOrder(); 86 | } 87 | if (right != null) { 88 | right.printPreOrder(); 89 | } 90 | } 91 | 92 | public void printPostOrder() { 93 | if (left != null) { 94 | left.printPostOrder(); 95 | } 96 | if (right != null) { 97 | right.printPostOrder(); 98 | } 99 | System.out.print(data + " "); 100 | } 101 | 102 | /** 103 | * O(n) time algorithm. 104 | * Uses O(n) space to store nodes in a queue to aid in traversal. 105 | */ 106 | public void printLevelOrder() { 107 | LinkedList queue = new LinkedList<>(); 108 | queue.add(this); 109 | while (queue.size() > 0) { 110 | Node head = queue.remove(); 111 | System.out.print(head.data + " "); 112 | // Add children of recently-printed node to queue, if they exist. 113 | if (head.left != null) { 114 | queue.add(head.left); 115 | } 116 | if (head.right != null) { 117 | queue.add(head.right); 118 | } 119 | } 120 | } 121 | } 122 | --------------------------------------------------------------------------------