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 | * @author Nicolas Renard
14 | *
15 | *
16 | */
17 | public interface Heap {
18 |
19 | /**
20 | *
21 | * @return the top element in the heap, the one with lowest key for min-heap or with
22 | * the highest key for max-heap
23 | * @throws Exception if heap is empty
24 | */
25 | public abstract HeapElement getElement() throws EmptyHeapException;
26 | /**
27 | * Inserts an element in the heap. Adds it to then end and toggle it until it finds its
28 | * right position.
29 | *
30 | * @param element an instance of the HeapElement class.
31 | */
32 | public abstract void insertElement(HeapElement element);
33 |
34 | /**
35 | * Delete an element in the heap.
36 | *
37 | * @param elementIndex int containing the position in the heap of the element to be deleted.
38 | */
39 | public abstract void deleteElement(int elementIndex);
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/Conversions/DecimalToBinary.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | * This class converts a Decimal number to a Binary number
5 | *
6 | * @author Unknown
7 | *
8 | */
9 | class DecimalToBinary {
10 |
11 | /**
12 | * Main Method
13 | *
14 | * @param args Command Line Arguments
15 | */
16 | public static void main(String args[]) {
17 | conventionalConversion();
18 | bitwiseConversion();
19 | }
20 |
21 | /**
22 | * This method converts a decimal number
23 | * to a binary number using a conventional
24 | * algorithm.
25 | */
26 | public static void conventionalConversion() {
27 | int n, b = 0, c = 0, d;
28 | Scanner input = new Scanner(System.in);
29 | System.out.printf("Conventional conversion.\n\tEnter the decimal number: ");
30 | n = input.nextInt();
31 | while (n != 0) {
32 | d = n % 2;
33 | b = b + d * (int) Math.pow(10, c++);
34 | n /= 2;
35 | } //converting decimal to binary
36 | System.out.println("\tBinary number: " + b);
37 | }
38 |
39 | /**
40 | * This method converts a decimal number
41 | * to a binary number using a bitwise
42 | * algorithm
43 | */
44 | public static void bitwiseConversion() {
45 | int n, b = 0, c = 0, d;
46 | Scanner input = new Scanner(System.in);
47 | System.out.printf("Bitwise conversion.\n\tEnter the decimal number: ");
48 | n = input.nextInt();
49 | while (n != 0) {
50 | d = (n & 1);
51 | b += d * (int) Math.pow(10, c++);
52 | n >>= 1;
53 | }
54 | System.out.println("\tBinary number: " + b);
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/Sorts/ShellSort.java:
--------------------------------------------------------------------------------
1 | package Sorts;
2 |
3 | /**
4 | * @author dpunosevac
5 | */
6 | public class ShellSort {
7 |
8 | /**
9 | * This method implements Generic Shell Sort.
10 | * @param array The array to be sorted
11 | */
12 | public static void shellSort(Comparable[] array) {
13 | int N = array.length;
14 | int h = 1;
15 |
16 | while (h < N/3) {
17 | h = 3 * h + 1;
18 | }
19 |
20 | while (h >= 1) {
21 | for (int i = h; i < N; i++) {
22 | for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) {
23 | exch(array, j, j - h);
24 | }
25 | }
26 |
27 | h /= 3;
28 | }
29 | }
30 |
31 | /**
32 | * Helper method for exchanging places in array
33 | * @param array The array which elements we want to swap
34 | * @param i index of the first element
35 | * @param j index of the second element
36 | */
37 | private static void exch(Comparable[] array, int i, int j) {
38 | Comparable swap = array[i];
39 | array[i] = array[j];
40 | array[j] = swap;
41 | }
42 |
43 | /**
44 | * This method checks if first element is less then the other element
45 | * @param v first element
46 | * @param w second element
47 | * @return true if the first element is less then the second element
48 | */
49 | private static boolean less(Comparable v, Comparable w) {
50 | return v.compareTo(w) < 0;
51 | }
52 |
53 | public static void main(String[] args) {
54 | // Integer Input
55 | int[] arr1 = {4,23,6,78,1,54,231,9,12};
56 | Integer[] array = new Integer[arr1.length];
57 |
58 | for (int i=0;i> void IS(T array[], int last) {
18 | T key;
19 | for (int j=1;j=0 && key.compareTo(array[i]) < 0) {
25 | array[i+1] = array[i];
26 | i--;
27 | }
28 | // Placing the key (Card) at its correct position in the sorted subarray
29 | array[i+1] = key;
30 | }
31 | }
32 |
33 | // Driver Program
34 | public static void main(String[] args) {
35 | // Integer Input
36 | int[] arr1 = {4,23,6,78,1,54,231,9,12};
37 | int last = arr1.length;
38 | Integer[] array = new Integer[arr1.length];
39 | for (int i=0;i 1 4 6 9 12 23 54 78 231
46 | for (int i=0;i a b c d e
58 | for(int i=0; i> void SS(T[] arr, int n) {
18 |
19 | for (int i=0;i 1 4 6 9 12 23 54 78 231
54 | for(int i=0; i a b c d e
68 | for(int i=0; i=0; i--) {
36 | if (valOfChar(inp_num.charAt(i)) >= base) {
37 | return "Invalid Number";
38 | }
39 | num += valOfChar(inp_num.charAt(i))*pow;
40 | pow *= base;
41 | }
42 | return String.valueOf(num);
43 | }
44 |
45 | /**
46 | * This method produces integer value of the input character and returns it
47 | * @param c Char of which we need the integer value of
48 | * @return integer value of input char
49 | */
50 |
51 | public static int valOfChar(char c) {
52 | if (c >= '0' && c <= '9') {
53 | return (int)c - '0';
54 | }
55 | else {
56 | return (int)c - 'A' + 10;
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Dynamic Programming/LongestIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | *
5 | * @author Afrizal Fikri (https://github.com/icalF)
6 | *
7 | */
8 | public class LongestIncreasingSubsequence {
9 | public static void main(String[] args) throws Exception {
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 | int length = 1; // always points empty slot in tail
41 |
42 | tail[0] = array[0];
43 | for (int i = 1; i < N; i++) {
44 |
45 | // new smallest value
46 | if (array[i] < tail[0])
47 | tail[0] = array[i];
48 |
49 | // array[i] extends largest subsequence
50 | else if (array[i] > tail[length-1])
51 | tail[length++] = array[i];
52 |
53 | // array[i] will become end candidate of an existing subsequence or
54 | // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
55 | // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
56 | else
57 | tail[upperBound(tail, -1, length-1, array[i])] = array[i];
58 | }
59 |
60 | return length;
61 | }
62 | }
--------------------------------------------------------------------------------
/Data Structures/Trees/ValidBSTOrNot.java:
--------------------------------------------------------------------------------
1 | class Node
2 | {
3 | int data;
4 | Node left, right;
5 |
6 | public Node(int item)
7 | {
8 | data = item;
9 | left = right = null;
10 | }
11 | }
12 |
13 | public class ValidBSTOrNot
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 | {
32 | /* an empty tree is BST */
33 | if (node == null)
34 | return true;
35 |
36 | /* false if this node violates the min/max constraints */
37 | if (node.data < min || node.data > max)
38 | return false;
39 |
40 | /* otherwise check the subtrees recursively
41 | tightening the min/max constraints */
42 | // Allow only distinct values
43 | return (isBSTUtil(node.left, min, node.data-1) &&
44 | isBSTUtil(node.right, node.data+1, max));
45 | }
46 |
47 | /* Driver program to test above functions */
48 | public static void main(String args[])
49 | {
50 | ValidBSTOrNot tree = new ValidBSTOrNot();
51 | tree.root = new Node(4);
52 | tree.root.left = new Node(2);
53 | tree.root.right = new Node(5);
54 | tree.root.left.left = new Node(1);
55 | tree.root.left.right = new Node(3);
56 |
57 | if (tree.isBST())
58 | System.out.println("IS BST");
59 | else
60 | System.out.println("Not a BST");
61 | }
62 | }
--------------------------------------------------------------------------------
/Searches/BinarySearch.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | *
5 | * @author Varun Upadhyay (https://github.com/varunu28)
6 | *
7 | */
8 |
9 | class BinarySearch
10 | {
11 | /**
12 | * This method implements the Generic Binary Search
13 | *
14 | * @param array The array to make the binary search
15 | * @param key The number you are looking for
16 | * @param lb The lower bound
17 | * @param ub The upper bound
18 | * @return the location of the key
19 | **/
20 |
21 | public static > int BS(T array[], T key, int lb, int ub)
22 | {
23 | if ( lb > ub)
24 | return -1;
25 |
26 | int mid = (ub+lb) >>> 1;
27 | int comp = key.compareTo(array[mid]);
28 |
29 | if (comp < 0)
30 | return (BS(array, key, lb, mid-1));
31 |
32 | if (comp > 0)
33 | return (BS(array, key, mid + 1, ub));
34 |
35 | return mid;
36 | }
37 |
38 | // Driver Program
39 | public static void main(String[] args)
40 | {
41 | Scanner input=new Scanner(System.in);
42 |
43 | // For INTEGER Input
44 | Integer[] array = new Integer[10];
45 | int key = 5;
46 |
47 | for (int i = 0; i < 10 ; i++ )
48 | array[i] = i+1;
49 |
50 | int index = BS(array, key, 0, 9);
51 |
52 | if (index != -1)
53 | System.out.println("Number " + key + " found at index number : " + index);
54 | else
55 | System.out.println("Not found");
56 |
57 |
58 | // For STRING Input
59 | String[] array1 = {"a", "b", "c", "d", "e"};
60 | String key1 = "d";
61 |
62 | int index1 = BS(array1, key1, 0, array1.length-1);
63 |
64 | if (index1 != -1)
65 | System.out.println("String " + key1 + " found at index number : " + index1);
66 | else
67 | System.out.println("Not found");
68 |
69 | input.close();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Data Structures/Trees/LevelOrderTraversalQueue.java:
--------------------------------------------------------------------------------
1 | import java.util.Queue;
2 | import java.util.LinkedList;
3 |
4 | /* Class to represent Tree node */
5 | class Node {
6 | int data;
7 | Node left, right;
8 |
9 | public Node(int item) {
10 | data = item;
11 | left = null;
12 | right = null;
13 | }
14 | }
15 |
16 | /* Class to print Level Order Traversal */
17 | public class LevelOrderTraversalQueue {
18 |
19 | Node root;
20 |
21 | /* Given a binary tree. Print its nodes in level order
22 | using array for implementing queue */
23 | void printLevelOrder()
24 | {
25 | Queue queue = new LinkedList();
26 | queue.add(root);
27 | while (!queue.isEmpty())
28 | {
29 |
30 | /* poll() removes the present head.
31 | For more information on poll() visit
32 | http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
33 | Node tempNode = queue.poll();
34 | System.out.print(tempNode.data + " ");
35 |
36 | /*Enqueue left child */
37 | if (tempNode.left != null) {
38 | queue.add(tempNode.left);
39 | }
40 |
41 | /*Enqueue right child */
42 | if (tempNode.right != null) {
43 | queue.add(tempNode.right);
44 | }
45 | }
46 | }
47 |
48 | public static void main(String args[])
49 | {
50 | /* creating a binary tree and entering
51 | the nodes */
52 | LevelOrderTraversalQueue tree_level = new LevelOrderTraversalQueue();
53 | tree_level.root = new Node(1);
54 | tree_level.root.left = new Node(2);
55 | tree_level.root.right = new Node(3);
56 | tree_level.root.left.left = new Node(4);
57 | tree_level.root.left.right = new Node(5);
58 |
59 | System.out.println("Level order traversal of binary tree is - ");
60 | tree_level.printLevelOrder();
61 | }
62 | }
--------------------------------------------------------------------------------
/Sorts/BubbleSort.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * @author Varun Upadhyay (https://github.com/varunu28)
4 | *
5 | */
6 |
7 | class BubbleSort
8 | {
9 | /**
10 | * This method implements the Generic Bubble Sort
11 | *
12 | * @param array The array to be sorted
13 | * @param last The count of total number of elements in array
14 | * Sorts the array in increasing order
15 | **/
16 |
17 | public static > void BS(T array[], int last) {
18 | //Sorting
19 | boolean swap;
20 | do
21 | {
22 | swap = false;
23 | for (int count = 0; count < last-1; count++)
24 | {
25 | int comp = array[count].compareTo(array[count + 1]);
26 | if (comp > 0)
27 | {
28 | T temp = array[count];
29 | array[count] = array[count + 1];
30 | array[count + 1] = temp;
31 | swap = true;
32 | }
33 | }
34 | last--;
35 | } while (swap);
36 | }
37 |
38 | // Driver Program
39 | public static void main(String[] args)
40 | {
41 | // Integer Input
42 | int[] arr1 = {4,23,6,78,1,54,231,9,12};
43 | int last = arr1.length;
44 | Integer[] array = new Integer[last];
45 | for (int i=0;i 1 4 6 9 12 23 54 78 231
52 | for(int i=0; i a b c d e
65 | for(int i=0; i void swap(T array[], int first, int second){
7 | T randomElement = array[first];
8 | array[first] = array[second];
9 | array[second] = randomElement;
10 | }
11 |
12 | private static > boolean isSorted(T array[]){
13 | for(int i = 0; i 0) return false;
15 | }
16 | return true;
17 | }
18 |
19 | // Randomly shuffles the array
20 | private static void nextPermutation(T array[]){
21 | int length = array.length;
22 | Random random = new Random();
23 |
24 | for (int i = 0; i < array.length; i++) {
25 | int randomIndex = i + random.nextInt(length - i);
26 | swap(array, randomIndex, i);
27 | }
28 | }
29 |
30 | public static > void bogoSort(T array[]) {
31 | while(!isSorted(array)){
32 | nextPermutation(array);
33 | }
34 | }
35 |
36 | // Driver Program
37 | public static void main(String[] args)
38 | {
39 | // Integer Input
40 | int[] arr1 = {4,23,6,78,1,54,231,9,12};
41 | int last = arr1.length;
42 | Integer[] array = new Integer[last];
43 | for (int i=0;i 1 4 6 9 12 23 54 78 231
50 | for(int i=0; i a b c d e
63 | for(int i=0; i0)
45 | {
46 | now=q%8;
47 | octnum=(now*(int)(Math.pow(10,i)))+octnum;
48 | q/=8;
49 | i++;
50 | }
51 | octnum/=10;
52 | return octnum;
53 | }
54 | // Main method that gets the hex input from user and converts it into octal.
55 | public static void main(String args[])
56 | {
57 | String hexadecnum;
58 | int decnum,octalnum;
59 | Scanner scan = new Scanner(System.in);
60 |
61 | System.out.print("Enter Hexadecimal Number : ");
62 | hexadecnum = scan.nextLine();
63 |
64 | // first convert hexadecimal to decimal
65 |
66 | decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
67 |
68 | // convert decimal to octal
69 | octalnum=decimal2octal(decnum);
70 | System.out.println("Number in octal: "+octalnum);
71 |
72 |
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Dynamic Programming/Fibonacci.java:
--------------------------------------------------------------------------------
1 | import java.io.BufferedReader;
2 | import java.io.InputStreamReader;
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | *
8 | * @author Varun Upadhyay (https://github.com/varunu28)
9 | *
10 | */
11 |
12 | public class Fibonacci {
13 |
14 | private static Map map = new HashMap();
15 |
16 | public static void main(String[] args) throws Exception {
17 |
18 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
19 | int n = Integer.parseInt(br.readLine());
20 |
21 | System.out.println(fibMemo(n)); // Returns 8 for n = 6
22 | System.out.println(fibBotUp(n)); // Returns 8 for n = 6
23 | }
24 |
25 | /**
26 | * This method finds the nth fibonacci number using memoization technique
27 | *
28 | * @param n The input n for which we have to determine the fibonacci number
29 | * Outputs the nth fibonacci number
30 | **/
31 |
32 | private static int fibMemo(int n) {
33 | if (map.containsKey(n)) {
34 | return map.get(n);
35 | }
36 |
37 | int f;
38 |
39 | if (n <= 2) {
40 | f = 1;
41 | }
42 | else {
43 | f = fibMemo(n-1) + fibMemo(n-2);
44 | map.put(n,f);
45 | }
46 |
47 | return f;
48 | }
49 |
50 | /**
51 | * This method finds the nth fibonacci number using bottom up
52 | *
53 | * @param n The input n for which we have to determine the fibonacci number
54 | * Outputs the nth fibonacci number
55 | **/
56 |
57 | private static int fibBotUp(int n) {
58 |
59 | Map fib = new HashMap();
60 |
61 | for (int i=1;i lcsMatrix[i][j-1] ? lcsMatrix[i-1][j] : lcsMatrix[i][j-1];
29 | }
30 | }
31 | }
32 | return lcsString(str1, str2, lcsMatrix);
33 | }
34 |
35 | public static String lcsString (String str1, String str2, int[][] lcsMatrix) {
36 | StringBuilder lcs = new StringBuilder();
37 | int i = str1.length(),
38 | j = str2.length();
39 | while(i > 0 && j > 0) {
40 | if(str1.charAt(i-1) == str2.charAt(j-1)) {
41 | lcs.append(str1.charAt(i-1));
42 | i--;
43 | j--;
44 | } else if(lcsMatrix[i-1][j] > lcsMatrix[i][j-1]) {
45 | i--;
46 | } else {
47 | j--;
48 | }
49 | }
50 | return lcs.reverse().toString();
51 | }
52 |
53 | public static void main(String[] args) {
54 | String str1 = "DSGSHSRGSRHTRD";
55 | String str2 = "DATRGAGTSHS";
56 | String lcs = getLCS(str1, str2);
57 |
58 | //Print LCS
59 | if(lcs != null) {
60 | System.out.println("String 1: " + str1);
61 | System.out.println("String 2: " + str2);
62 | System.out.println("LCS: " + lcs);
63 | System.out.println("LCS length: " + lcs.length());
64 | }
65 | }
66 | }
--------------------------------------------------------------------------------
/ciphers/RSA.java:
--------------------------------------------------------------------------------
1 | package ciphers;
2 |
3 | import java.math.BigInteger;
4 | import java.security.SecureRandom;
5 |
6 | /**
7 | * Created by Nguyen Duy Tiep on 23-Oct-17.
8 | */
9 | public class RSA {
10 | private BigInteger modulus, privateKey, publicKey;
11 |
12 | public RSA(int bits) {
13 | generateKeys(bits);
14 | }
15 |
16 | public synchronized String encrypt(String message) {
17 | return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
18 | }
19 |
20 | public synchronized BigInteger encrypt(BigInteger message) {
21 | return message.modPow(publicKey, modulus);
22 | }
23 |
24 | public synchronized String decrypt(String message) {
25 | return new String((new BigInteger(message)).modPow(privateKey, modulus).toByteArray());
26 | }
27 |
28 | public synchronized BigInteger decrypt(BigInteger message) {
29 | return message.modPow(privateKey, modulus);
30 | }
31 |
32 | /** Generate a new public and private key set. */
33 | public synchronized void generateKeys(int bits) {
34 | SecureRandom r = new SecureRandom();
35 | BigInteger p = new BigInteger(bits / 2, 100, r);
36 | BigInteger q = new BigInteger(bits / 2, 100, r);
37 | modulus = p.multiply(q);
38 |
39 | BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
40 |
41 | publicKey = new BigInteger("3");
42 |
43 | while (m.gcd(publicKey).intValue() > 1) {
44 | publicKey = publicKey.add(new BigInteger("2"));
45 | }
46 |
47 | privateKey = publicKey.modInverse(m);
48 | }
49 |
50 | /** Trivial test program. */
51 | public static void main(String[] args) {
52 | RSA rsa = new RSA(1024);
53 |
54 | String text1 = "This is a message";
55 | System.out.println("Plaintext: " + text1);
56 |
57 | String ciphertext = rsa.encrypt(text1);
58 | System.out.println("Ciphertext: " + ciphertext);
59 |
60 | System.out.println("Plaintext: " + rsa.decrypt(ciphertext));
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Others/ReverseStackUsingRecursion.java:
--------------------------------------------------------------------------------
1 | /* Program to reverse a Stack using Recursion*/
2 |
3 |
4 | import java.util.Stack;
5 |
6 | public class ReverseStackUsingRecursion {
7 |
8 | //Stack
9 | private static Stack stack=new Stack<>();
10 |
11 | //Main function
12 | public static void main(String[] args) {
13 | //To Create a Dummy Stack containing integers from 0-9
14 | for(int i=0;i<10;i++)
15 | {
16 | stack.push(i);
17 | }
18 | System.out.println("STACK");
19 |
20 | //To print that dummy Stack
21 | for(int k=9;k>=0;k--)
22 | {
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 | {
33 | System.out.println(stack.pop());
34 | }
35 |
36 |
37 | }
38 |
39 | //Function Used to reverse Stack Using Recursion
40 | private static void reverseUsingRecursion(Stack stack) {
41 | if(stack.isEmpty()) // If stack is empty then return
42 | {
43 | return;
44 | }
45 | /* All items are stored in call stack until we reach the end*/
46 |
47 | int temptop=stack.peek();
48 | stack.pop();
49 | reverseUsingRecursion(stack); //Recursion call
50 | insertAtEnd(temptop); // Insert items held in call stack one by one into stack
51 | }
52 |
53 | //Function used to insert element at the end of stack
54 | private static void insertAtEnd(int temptop) {
55 | if(stack.isEmpty())
56 | {
57 | stack.push(temptop); // If stack is empty push the element
58 | }
59 | else {
60 | int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/
61 | stack.pop();
62 |
63 | insertAtEnd(temptop); //Recursive call
64 |
65 | stack.push(temp);
66 | }
67 |
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/Data Structures/Graphs/BFS.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | /**
4 | * Implementation of a Breadth First Search
5 | *
6 | * @author Unknown
7 | *
8 | */
9 | public class BFS{
10 |
11 | /**
12 | * The BFS implemented in code to use.
13 | *
14 | * @param a Structure to perform the search on a graph, adjacency matrix etc.
15 | * @param vertices The vertices to use
16 | * @param source The Source
17 | */
18 | public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
19 | byte []b=new byte[vertices]; //flag container containing status of each vertices
20 | Arrays.fill(b,(byte)-1); //status initialization
21 | /* code status
22 | -1 = ready
23 | 0 = waiting
24 | 1 = processed */
25 |
26 | Stack st = new Stack(vertices); //operational stack
27 | st.push(source); //assigning source
28 | while(!st.isEmpty()){
29 | b[st.peek()]=(byte)0; //assigning waiting status
30 | System.out.println(st.peek());
31 | int pop=st.peek();
32 | b[pop]=(byte)1; //assigning processed status
33 | st.pop(); //removing head of the queue
34 | for(int i=0;i> void CS(T array[], int last) {
20 |
21 | // Sorting
22 | boolean swap;
23 | do {
24 | swap = false;
25 |
26 | //front
27 | for (int count = 0; count <= last - 2; count++) {
28 | int comp = array[count].compareTo(array[count + 1]);
29 | if (comp > 0) {
30 | T aux = array[count];
31 | array[count] = array[count + 1];
32 | array[count + 1] = aux;
33 | swap = true;
34 | }
35 | }
36 | //break if no swap occurred
37 | if (!swap) {
38 | break;
39 | }
40 | swap = false;
41 |
42 | //back
43 | for (int count = last - 2; count >= 0; count--) {
44 | int comp = array[count].compareTo(array[count + 1]);
45 | if (comp > 0) {
46 | T aux = array[count];
47 | array[count] = array[count + 1];
48 | array[count + 1] = aux;
49 | swap = true;
50 | }
51 | }
52 | last--;
53 | //end
54 | } while (swap);
55 | }
56 |
57 | // Driver Program
58 | public static void main(String[] args) {
59 | // Integer Input
60 | int[] arr1 = { 4, 23, 6, 78, 1, 54, 231, 9, 12 };
61 | int last = arr1.length;
62 | Integer[] array = new Integer[last];
63 | for (int i = 0; i < last; i++) {
64 | array[i] = arr1[i];
65 | }
66 |
67 | CS(array, last);
68 |
69 | // Output => 1 4 6 9 12 23 54 78 231
70 | for (int i = 0; i < last; i++) {
71 | System.out.print(array[i] + "\t");
72 | }
73 | System.out.println();
74 |
75 | // String Input
76 | String[] array1 = { "c", "a", "e", "b", "d" };
77 | last = array1.length;
78 |
79 | CS(array1, last);
80 |
81 | // Output => a b c d e
82 | for (int i = 0; i < last; i++) {
83 | System.out.print(array1[i] + "\t");
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/Misc/heap_sort.java:
--------------------------------------------------------------------------------
1 | public class heap_sort
2 | {
3 | public void sort(int arr[])
4 | {
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 | {
14 | // Move current root to end
15 | int temp = arr[0];
16 | arr[0] = arr[i];
17 | arr[i] = temp;
18 |
19 | // call max heapify on the reduced heap
20 | heapify(arr, i, 0);
21 | }
22 | }
23 |
24 | // To heapify a subtree rooted with node i which is
25 | // an index in arr[]. n is size of heap
26 | void heapify(int arr[], int n, int i)
27 | {
28 | int largest = i; // Initialize largest as root
29 | int l = 2*i + 1; // left = 2*i + 1
30 | int r = 2*i + 2; // right = 2*i + 2
31 |
32 | // If left child is larger than root
33 | if (l < n && arr[l] > arr[largest])
34 | largest = l;
35 |
36 | // If right child is larger than largest so far
37 | if (r < n && arr[r] > arr[largest])
38 | largest = r;
39 |
40 | // If largest is not root
41 | if (largest != i)
42 | {
43 | int swap = arr[i];
44 | arr[i] = arr[largest];
45 | arr[largest] = swap;
46 |
47 | // Recursively heapify the affected sub-tree
48 | heapify(arr, n, largest);
49 | }
50 | }
51 |
52 | /* A utility function to print array of size n */
53 | static void printArray(int arr[])
54 | {
55 | int n = arr.length;
56 | for (int i=0; i charArr = new ArrayList<>();
37 |
38 | while (inp > 0) {
39 | charArr.add(reVal(inp%base));
40 | inp /= base;
41 | }
42 |
43 | StringBuilder str = new StringBuilder(charArr.size());
44 |
45 | for(Character ch: charArr)
46 | {
47 | str.append(ch);
48 | }
49 |
50 | return str.reverse().toString();
51 | }
52 |
53 | /**
54 | * This method produces character value of the input integer and returns it
55 | * @param num integer of which we need the character value of
56 | * @return character value of input integer
57 | */
58 |
59 | public static char reVal(int num) {
60 | if (num >= 0 && num <= 9)
61 | return (char)(num + '0');
62 | else
63 | return (char)(num - 10 + 'A');
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Others/LinearCongruentialGenerator.java:
--------------------------------------------------------------------------------
1 | /***
2 | * A pseudorandom number generator.
3 | *
4 | * @author Tobias Carryer
5 | * Date: October 10, 2017
6 | */
7 | public class LinearCongruentialGenerator {
8 |
9 | private double a, c, m, previousValue;
10 |
11 | /***
12 | * These parameters are saved and used when nextNumber() is called.
13 | * The current timestamp in milliseconds is used as the seed.
14 | *
15 | * @param multiplier
16 | * @param increment
17 | * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
18 | */
19 | public LinearCongruentialGenerator( double multiplier, double increment, double modulo ) {
20 | this(System.currentTimeMillis(), multiplier, increment, modulo);
21 | }
22 |
23 | /***
24 | * These parameters are saved and used when nextNumber() is called.
25 | *
26 | * @param seed
27 | * @param multiplier
28 | * @param increment
29 | * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
30 | */
31 | public LinearCongruentialGenerator( double seed, double multiplier, double increment, double modulo ) {
32 | this.previousValue = seed;
33 | this.a = multiplier;
34 | this.c = increment;
35 | this.m = modulo;
36 | }
37 |
38 | /**
39 | * The smallest number that can be generated is zero.
40 | * The largest number that can be generated is modulo-1. modulo is set in the constructor.
41 | * @return a pseudorandom number.
42 | */
43 | public double nextNumber() {
44 | previousValue = (a * previousValue + c) % m;
45 | return previousValue;
46 | }
47 |
48 | public static void main( String[] args ) {
49 | // Show the LCG in action.
50 | // Decisive proof that the LCG works could be made by adding each number
51 | // generated to a Set while checking for duplicates.
52 | LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
53 | for( int i = 0; i < 512; i++ ) {
54 | System.out.println(lcg.nextNumber());
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Data Structures/Stacks/StackOfLinkedList.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * @author Varun Upadhyay (https://github.com/varunu28)
4 | *
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 |
19 | stack.printStack();
20 |
21 | System.out.println("Size of stack currently is: " + stack.getSize());
22 |
23 | stack.pop();
24 | stack.pop();
25 |
26 | }
27 |
28 | }
29 |
30 | // A node class
31 |
32 | class Node {
33 | public int data;
34 | public Node next;
35 |
36 | public Node(int data) {
37 | this.data = data;
38 | this.next = null;
39 | }
40 | }
41 |
42 | /**
43 | * A class which implements a stack using a linked list
44 | *
45 | * Contains all the stack methods : push, pop, printStack, isEmpty
46 | **/
47 |
48 | class LinkedListStack {
49 |
50 | Node head = null;
51 | int size = 0;
52 |
53 | public void push(int x) {
54 | Node n = new Node(x);
55 | if (getSize() == 0) {
56 | head = n;
57 | }
58 | else {
59 | Node temp = head;
60 | n.next = temp;
61 | head = n;
62 | }
63 | size++;
64 | }
65 |
66 | public void pop() {
67 | if (getSize() == 0) {
68 | System.out.println("Empty stack. Nothing to pop");
69 | }
70 |
71 | Node temp = head;
72 | head = head.next;
73 | size--;
74 |
75 | System.out.println("Popped element is: " + temp.data);
76 | }
77 |
78 | public void printStack() {
79 |
80 | Node temp = head;
81 | System.out.println("Stack is printed as below: ");
82 | while (temp != null) {
83 | System.out.print(temp.data + " ");
84 | temp = temp.next;
85 | }
86 | System.out.println();
87 |
88 | }
89 |
90 | public boolean isEmpty() {
91 | return getSize() == 0;
92 | }
93 |
94 | public int getSize() {
95 | return size;
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/Data Structures/Trees/LevelOrderTraversal.java:
--------------------------------------------------------------------------------
1 | class Node
2 | {
3 | int data;
4 | Node left, right;
5 | public Node(int item)
6 | {
7 | data = item;
8 | left = right = null;
9 | }
10 | }
11 |
12 | public class LevelOrderTraversal
13 | {
14 | // Root of the Binary Tree
15 | Node root;
16 |
17 | public LevelOrderTraversal()
18 | {
19 | root = null;
20 | }
21 |
22 | /* function to print level order traversal of tree*/
23 | void printLevelOrder()
24 | {
25 | int h = height(root);
26 | int i;
27 | for (i=1; i<=h; i++)
28 | printGivenLevel(root, i);
29 | }
30 |
31 | /* Compute the "height" of a tree -- the number of
32 | nodes along the longest path from the root node
33 | down to the farthest leaf node.*/
34 | int height(Node root)
35 | {
36 | if (root == null)
37 | return 0;
38 | else
39 | {
40 | /* compute height of each subtree */
41 | int lheight = height(root.left);
42 | int rheight = height(root.right);
43 |
44 | /* use the larger one */
45 | if (lheight > rheight)
46 | return(lheight+1);
47 | else return(rheight+1);
48 | }
49 | }
50 |
51 | /* Print nodes at the given level */
52 | void printGivenLevel (Node root ,int level)
53 | {
54 | if (root == null)
55 | return;
56 | if (level == 1)
57 | System.out.print(root.data + " ");
58 | else if (level > 1)
59 | {
60 | printGivenLevel(root.left, level-1);
61 | printGivenLevel(root.right, level-1);
62 | }
63 | }
64 |
65 | /* Driver program to test above functions */
66 | public static void main(String args[])
67 | {
68 | LevelOrderTraversal tree = new LevelOrderTraversal();
69 | tree.root= new Node(1);
70 | tree.root.left= new Node(2);
71 | tree.root.right= new Node(3);
72 | tree.root.left.left= new Node(4);
73 | tree.root.left.right= new Node(5);
74 |
75 | System.out.println("Level order traversal of binary tree is ");
76 | tree.printLevelOrder();
77 | }
78 | }
--------------------------------------------------------------------------------
/Searches/SaddlebackSearch.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | /**
4 | * Program to perform Saddleback Search
5 | * Given a sorted 2D array(elements are sorted across every row and column, assuming ascending order)
6 | * of size n*m we can search a given element in O(n+m)
7 | *
8 | * we start from bottom left corner
9 | * if the current element is greater than the given element then we move up
10 | * else we move right
11 | * Sample Input:
12 | * 5 5 ->Dimensions
13 | * -10 -5 -3 4 9
14 | * -6 -2 0 5 10
15 | * -4 -1 1 6 12
16 | * 2 3 7 8 13
17 | * 100 120 130 140 150
18 | * 140 ->element to be searched
19 | * output: 4 3 // first value is row, second one is column
20 | *
21 | * @author Nishita Aggarwal
22 | *
23 | */
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 crow the current row.
32 | * @param ccol the current column.
33 | * @param ele the element that we want to search for.
34 | *
35 | * @return The index(row and column) of the element if found.
36 | * Else returns -1 -1.
37 | */
38 | static int[] search(int arr[][],int crow,int ccol,int ele){
39 |
40 | //array to store the answer row and column
41 | int ans[]={-1,-1};
42 | if(crow<0 || ccol>=arr[crow].length){
43 | return ans;
44 | }
45 | if(arr[crow][ccol]==ele)
46 | {
47 | ans[0]=crow;
48 | ans[1]=ccol;
49 | return ans;
50 | }
51 | //if the current element is greater than the given element then we move up
52 | else if(arr[crow][ccol]>ele)
53 | {
54 | return search(arr,crow-1,ccol,ele);
55 | }
56 | //else we move right
57 | return search(arr,crow,ccol+1,ele);
58 | }
59 |
60 | /**
61 | * Main method
62 | *
63 | * @param args Command line arguments
64 | */
65 | public static void main(String[] args) {
66 | // TODO Auto-generated method stub
67 | Scanner sc=new Scanner(System.in);
68 | int arr[][];
69 | int i,j,rows=sc.nextInt(),col=sc.nextInt();
70 | arr=new int[rows][col];
71 | for(i=0;i{
2 | private static class Node{
3 | Node next;
4 | E value;
5 | private Node(E value, Node next){
6 | this.value = value;
7 | this.next = next;
8 | }
9 | }
10 | //For better O.O design this should be private allows for better black box design
11 | private int size;
12 | //this will point to dummy node;
13 | private Node head;
14 | //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;
15 | public CircleLinkedList(){
16 | //creation of the dummy node
17 | head = new Node(null,head);
18 | size = 0;
19 | }
20 | // getter for the size... needed because size is private.
21 | public int getSize(){ return size;}
22 | // 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.
23 | public void append(E value){
24 | if(value == null){
25 | // we do not want to add null elements to the list.
26 | throw new NullPointerException("Cannot add null element to the list");
27 | }
28 | //head.next points to the last element;
29 | head.next = new Node(value,head);
30 | size++;}
31 | public E remove(int pos){
32 | if(pos>size || pos< 0){
33 | //catching errors
34 | throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
35 | }
36 | Node iterator = head.next;
37 | //we need to keep track of the element before the element we want to remove we can see why bellow.
38 | Node before = head;
39 | for(int i = 1; i<=pos; i++){
40 | iterator = iterator.next;
41 | before = before.next;
42 | }
43 | E saved = iterator.value;
44 | // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
45 | before.next = iterator.next;
46 | // scrubbing
47 | iterator.next = null;
48 | iterator.value = null;
49 | return saved;
50 |
51 | }
52 |
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/Others/Dijkshtra.java:
--------------------------------------------------------------------------------
1 | /*
2 | @author : Mayank K Jha
3 |
4 | */
5 |
6 |
7 | import java.io.IOException;
8 | import java.util.Arrays;
9 | import java.util.Scanner;
10 | import java.util.Stack;
11 |
12 | public class Dijkshtra {
13 |
14 | public static void main(String[] args) throws IOException {
15 | Scanner in =new Scanner(System.in);
16 |
17 | int n=in.nextInt(); //n = Number of nodes or vertices
18 | int m=in.nextInt(); //m = Number of Edges
19 | long w[][]=new long [n+1][n+1]; //Adjacency Matrix
20 |
21 | //Initializing Matrix with Certain Maximum Value for path b/w any two vertices
22 | for (long[] row: w)
23 | Arrays.fill(row, 1000000l);
24 | //From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
25 | //For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l .
26 |
27 | //Taking Input as Edge Location b/w a pair of vertices
28 | for(int i=0;icmp){ //Comparing previous edge value with current value - Cycle Case
32 | w[x][y]=cmp; w[y][x]=cmp;
33 | }
34 | }
35 |
36 | //Implementing Dijkshtra's Algorithm
37 |
38 | Stack t=new Stack();
39 | int src=in.nextInt();
40 | for(int i=1;i<=n;i++){
41 | if(i!=src){t.push(i);}}
42 | Stack p=new Stack();
43 | p.push(src);
44 | w[src][src]=0;
45 | while(!t.isEmpty()){int min=989997979,loc=-1;
46 | for(int i=0;i> int linearSearch(T[] array, T value) {
68 | int lo = 0;
69 | int hi = array.length - 1;
70 | for (int i = lo; i <= hi; i++) {
71 | if (array[i].compareTo(value) == 0) {
72 | return i;
73 | }
74 | }
75 | return -1;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/Searches/TernarySearch.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class TernarySearch{
4 |
5 | /**
6 | * @param arr The **Sorted** array in which we will search the element.
7 | * @param value The value that we want to search for.
8 | * @return The index of the element if found.
9 | * Else returns -1.
10 | */
11 | public static int ternarySearch(int[] arr, int value){
12 | return ternarySearch(arr, value, 0, arr.length - 1);
13 | }
14 |
15 | /**
16 | * @param arr The **Sorted** array in which we will search the element.
17 | * @param key The value that we want to search for.
18 | * @param start The starting index from which we will start Searching.
19 | * @param end The ending index till which we will Search.
20 | * @return Returns the index of the Element if found.
21 | * Else returns -1.
22 | */
23 | public static int ternarySearch(int[] arr, int key, int start, int end) {
24 | if (start > end){
25 | return -1;
26 | }
27 | /* First boundary: add 1/3 of length to start */
28 | int mid1 = start + (end - start) / 3;
29 | /* Second boundary: add 2/3 of length to start */
30 | int mid2 = start + 2 * (end - start) / 3;
31 | if (arr[mid1] == key) {
32 | return mid1;
33 | }
34 | else if (arr[mid2] == key) {
35 | return mid2;
36 | }
37 |
38 | /* Search the first (1/3) rd part of the array.*/
39 |
40 | else if (key < arr[mid1]) {
41 | return ternarySearch(arr, key, start, mid1 - 1);
42 | }
43 | /* Search 3rd (1/3)rd part of the array */
44 |
45 | else if (key > arr[mid2]) {
46 | return ternarySearch(arr, key, mid2 + 1, end);
47 | }
48 | /* Search middle (1/3)rd part of the array */
49 |
50 | else {
51 | return ternarySearch(arr, key, mid1, mid2);
52 | }
53 | }
54 |
55 | public static void main(String[] args) {
56 | Scanner s = new Scanner(System.in);
57 | System.out.println("Enter number of elements in the array");
58 | int n = s.nextInt();
59 | int arr[] = new int[n];
60 | System.out.println("Enter the elements of the Sorted array");
61 | for (int i= 0; i < n; i++){
62 | arr[i] = s.nextInt();
63 | }
64 | System.out.println("Enter element to search for : ");
65 | int k = s.nextInt();
66 | int ans = ternarySearch(arr, k);
67 | if (ans == -1) {
68 | System.out.println(" The element is not present in the array.");
69 | }
70 | else {
71 | System.out.println("The element is present at the position " + (ans+1));
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/Sorts/CountingSort.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Map;
3 | import java.util.TreeMap;
4 |
5 | /**
6 | *
7 | * @author Youssef Ali (https://github.com/youssefAli11997)
8 | *
9 | */
10 |
11 | class CountingSort {
12 |
13 | /**
14 | * This method implements the Generic Counting Sort
15 | *
16 | * @param array The array to be sorted
17 | * @param last The count of total number of elements in array
18 | * Sorts the array in increasing order
19 | * It uses array elements as keys in the frequency map
20 | **/
21 |
22 | public static > void CS(T[] array, int last) {
23 |
24 | Map frequency = new TreeMap();
25 | // The final output array
26 | ArrayList sortedArray = new ArrayList();
27 |
28 | // Counting the frequency of @param array elements
29 | for(T t : array) {
30 | try{
31 | frequency.put(t, frequency.get(t)+1);
32 | }catch(Exception e){ // new entry
33 | frequency.put(t, 1);
34 | }
35 | }
36 |
37 | // Filling the sortedArray
38 | for(Map.Entry element : frequency.entrySet()) {
39 | for(int j=0; j 1 4 6 9 12 23 54 78 231
63 | System.out.println("After Sorting:");
64 | for (int i=0;i a b c d e
84 | System.out.println("After Sorting:");
85 | for(int i=0; i ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc
37 | * findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf
38 | */
39 | class Node {
40 | Node left, right;
41 | int data;
42 |
43 | public Node(int data) {
44 | this.data = data;
45 | }
46 |
47 | public void insert (int value) {
48 | if (value < data) {
49 | if (left == null) {
50 | left = new Node(value);
51 | }
52 | else {
53 | left.insert(value);
54 | }
55 | }
56 | else {
57 | if (right == null) {
58 | right = new Node(value);
59 | }
60 | else {
61 | right.insert(value);
62 | }
63 | }
64 | }
65 |
66 | public void printLevelOrder() {
67 | LinkedList queue = new LinkedList<>();
68 | queue.add(this);
69 | while(!queue.isEmpty()) {
70 | Node n = queue.poll();
71 | System.out.print(n.data + " ");
72 | if (n.left != null) {
73 | queue.add(n.left);
74 | }
75 | if (n.right != null) {
76 | queue.add(n.right);
77 | }
78 | }
79 | }
80 |
81 | public int findHeight() {
82 | return findHeight(this);
83 | }
84 |
85 | private int findHeight(Node root) {
86 | if (root.left == null && root.right == null) {
87 | return 0;
88 | }
89 | else if (root.left != null && root.right != null) {
90 | return 1 + Math.max(findHeight(root.left), findHeight(root.right));
91 | }
92 | else if (root.left == null && root.right != null) {
93 | return 1 + findHeight(root.right);
94 | }
95 | else {
96 | return 1 + findHeight(root.left);
97 | }
98 | }
99 | }
100 |
101 |
--------------------------------------------------------------------------------
/Sorts/BinaryTreeSort.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 | public class TreeSort {
3 |
4 | public Node root;
5 |
6 | public TreeSort(Object x) {
7 | root = new Node(x);
8 | }//end TreeSort constructor
9 |
10 | public Node insert(Node node, Integer x) {
11 | if (node == null) {
12 | return node = new Node(x);
13 | }//end if
14 | if (x < (Integer) node.anElement) {
15 | node.less = insert(node.less, x);
16 | } //end if
17 | else {
18 | node.greater = insert(node.greater, x);
19 | }//end else
20 | return node;
21 | }//end insert
22 |
23 |
24 | public Node decimalInsert(Node node, Double x) {
25 | if (node == null) {
26 | return node = new Node(x);
27 | }//end if
28 | if (x < (Double) node.anElement) {
29 | node.less = decimalInsert(node.less, x);
30 | } //end if
31 | else {
32 | node.greater = decimalInsert(node.greater, x);
33 | }//end else
34 | return node;
35 | }//end insert
36 |
37 |
38 | public void treeSort(Node node) {
39 | if (node != null) {
40 | treeSort(node.less);
41 | System.out.print(((Object) node.anElement) + ", ");
42 | treeSort(node.greater);
43 | }//end if
44 | }//end TreeSort class
45 |
46 |
47 |
48 | public static void main(String args[]) {
49 | int[] intArray = {12, 40, 9, 3, 19, 74, 7, 31, 23, 54, 26, 81, 12 };
50 | TreeSort ts = new TreeSort(new Integer(intArray[0]));
51 | for (int i = 1; i < intArray.length; i++) { //sorts every index of the list one at a time
52 | ts.insert(ts.root, new Integer(intArray[i])); //builds on the tree from a root node
53 | }//end for
54 | System.out.print("Integer Array Sorted in Increasing Order: ");
55 | ts.treeSort(ts.root);
56 | System.out.println(); //To sort a test array of integers
57 |
58 | Double[] decimalArray = {8.2, 1.5, 3.14159265, 9.3, 5.1, 4.8, 2.6};
59 | TreeSort dts = new TreeSort(new Double(decimalArray[0]).doubleValue());
60 | for (int i = 1; i < decimalArray.length; i++) { //sorts every index of the list one at a time
61 | dts.decimalInsert(dts.root, new Double(decimalArray[i]).doubleValue()); //builds on the tree from a root node
62 | }//end for
63 | System.out.print("Decimal Array, Sorted in Increasing Order: ");
64 | dts.treeSort(dts.root);
65 | System.out.println();
66 |
67 | String[] stringArray = {"c", "a", "e", "b","d", "dd","da","zz", "AA", "aa","aB","Hb", "Z"};
68 | int last = stringArray.length;
69 | Arrays.sort(stringArray); //Uses an imported arrays method to automatically alphabetize
70 | System.out.print("String Array Sorted in Alphabetical Order: ");
71 | ts.insert(ts.root, last);
72 | for(int i=0; i> void MS(T[] arr, T[] temp, int left, int right) {
20 | if (left < right) {
21 | int mid = left + (right - left) / 2;
22 | MS(arr, temp, left, mid);
23 | MS(arr, temp,mid + 1, right);
24 | merge(arr, temp, left, mid, right);
25 | }
26 |
27 | }
28 |
29 | /**
30 | * This method implements the merge step of the merge sort
31 | *
32 | * @param arr The array to be sorted
33 | * @param temp The copy of the actual array
34 | * @param left The first index of the array
35 | * @param mid The middle index of the array
36 | * @param right The last index of the array
37 | * merges two parts of an array in increasing order
38 | **/
39 |
40 | public static > void merge(T[] arr, T[] temp, int left, int mid, int right) {
41 | for (int i=left;i<=right;i++) {
42 | temp[i] = arr[i];
43 | }
44 |
45 | int i= left;
46 | int j = mid + 1;
47 | int k = left;
48 |
49 | while (i<=mid && j<=right) {
50 | if (temp[i].compareTo(temp[j]) <= 0) {
51 | arr[k] = temp[i];
52 | i++;
53 | }
54 | else {
55 | arr[k] = temp[j];
56 | j++;
57 | }
58 | k++;
59 | }
60 |
61 | while (i <= mid) {
62 | arr[k] = temp[i];
63 | i++;
64 | k++;
65 | }
66 | }
67 |
68 | // Driver program
69 | public static void main(String[] args) {
70 |
71 | // Integer Input
72 | int[] arr = {4,23,6,78,1,54,231,9,12};
73 | Integer[] array = new Integer[arr.length];
74 | for (int i=0;i 1 4 6 9 12 23 54 78 231
84 | for (int i=0;i a b c d e
95 | for(int i=0; i set = new HashSet<>();
50 |
51 | // Create a queue and add root to it
52 | Queue Q = new LinkedList();
53 | Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
54 |
55 | // Standard BFS or level order traversal loop
56 | while (!Q.isEmpty())
57 | {
58 | // Remove the front item and get its details
59 | QItem qi = Q.remove();
60 | int hd = qi.hd;
61 | TreeNode n = qi.node;
62 |
63 | // If this is the first node at its horizontal distance,
64 | // then this node is in top view
65 | if (!set.contains(hd))
66 | {
67 | set.add(hd);
68 | System.out.print(n.key + " ");
69 | }
70 |
71 | // Enqueue left and right children of current node
72 | if (n.left != null)
73 | Q.add(new QItem(n.left, hd-1));
74 | if (n.right != null)
75 | Q.add(new QItem(n.right, hd+1));
76 | }
77 | }
78 | }
79 |
80 | // Driver class to test above methods
81 | public class PrintTopViewofTree
82 | {
83 | public static void main(String[] args)
84 | {
85 | /* Create following Binary Tree
86 | 1
87 | / \
88 | 2 3
89 | \
90 | 4
91 | \
92 | 5
93 | \
94 | 6*/
95 | TreeNode root = new TreeNode(1);
96 | root.left = new TreeNode(2);
97 | root.right = new TreeNode(3);
98 | root.left.right = new TreeNode(4);
99 | root.left.right.right = new TreeNode(5);
100 | root.left.right.right.right = new TreeNode(6);
101 | Tree t = new Tree(root);
102 | System.out.println("Following are nodes in top view of Binary Tree");
103 | t.printTopView();
104 | }
105 | }
--------------------------------------------------------------------------------
/Data Structures/Queues/PriorityQueues.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This class implements a PriorityQueue.
3 | *
4 | * A priority queue adds elements into positions based on their priority.
5 | * So the most important elements are placed at the front/on the top.
6 | * In this example I give numbers that are bigger, a higher priority.
7 | * Queues in theory have no fixed size but when using an array
8 | * implementation it does.
9 | *
10 | * @author Unknown
11 | *
12 | */
13 | class PriorityQueue{
14 | /** The max size of the queue */
15 | private int maxSize;
16 | /** The array for the queue */
17 | private int[] queueArray;
18 | /** How many items are in the queue */
19 | private int nItems;
20 |
21 | /**
22 | * Constructor
23 | *
24 | * @param size Size of the queue
25 | */
26 | public PriorityQueue(int size){
27 | maxSize = size;
28 | queueArray = new int[size];
29 | nItems = 0;
30 | }
31 |
32 | /**
33 | * Inserts an element in it's appropriate place
34 | *
35 | * @param value Value to be inserted
36 | */
37 | public void insert(int value){
38 | if(nItems == 0){
39 | queueArray[0] = value;
40 | }
41 | else{
42 | int j = nItems;
43 | while(j > 0 && queueArray[j-1] > value){
44 | queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion
45 | j--;
46 | }
47 | queueArray[j] = value; //Once the correct position is found the value is inserted
48 | }
49 | nItems++;
50 | }
51 |
52 | /**
53 | * Remove the element from the front of the queue
54 | *
55 | * @return The element removed
56 | */
57 | public int remove(){
58 | return queueArray[--nItems];
59 | }
60 |
61 | /**
62 | * Checks what's at the front of the queue
63 | *
64 | * @return element at the front of the queue
65 | */
66 | public int peek(){
67 | return queueArray[nItems-1];
68 | }
69 |
70 | /**
71 | * Returns true if the queue is empty
72 | *
73 | * @return true if the queue is empty
74 | */
75 | public boolean isEmpty(){
76 | return(nItems == 0);
77 | }
78 |
79 | /**
80 | * Returns true if the queue is full
81 | *
82 | * @return true if the queue is full
83 | */
84 | public boolean isFull(){
85 | return(nItems == maxSize);
86 | }
87 |
88 | /**
89 | * Returns the number of elements in the queue
90 | *
91 | * @return number of elements in the queue
92 | */
93 | public int getSize(){
94 | return nItems;
95 | }
96 | }
97 |
98 | /**
99 | * This class implements the PriorityQueue class above.
100 | *
101 | * @author Unknown
102 | *
103 | */
104 | public class PriorityQueues{
105 | /**
106 | * Main method
107 | *
108 | * @param args Command Line Arguments
109 | */
110 | public static void main(String args[]){
111 | PriorityQueue myQueue = new PriorityQueue(4);
112 | myQueue.insert(10);
113 | myQueue.insert(2);
114 | myQueue.insert(5);
115 | myQueue.insert(3);
116 | //[2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
117 |
118 | for(int i = 3; i>=0; i--)
119 | System.out.print(myQueue.remove() + " "); //will print the queue in reverse order [10, 5, 3, 2]
120 |
121 | //As you can see, a Priority Queue can be used as a sorting algotithm
122 | }
123 | }
--------------------------------------------------------------------------------
/Data Structures/Bags/Bag.java:
--------------------------------------------------------------------------------
1 | package Bags;
2 |
3 | import java.util.Iterator;
4 | import java.util.NoSuchElementException;
5 |
6 | /**
7 | * Collection which does not allow removing elements (only collect and iterate)
8 | *
9 | * @param - the generic type of an element in this bag
10 | */
11 | public class Bag implements Iterable {
12 |
13 | private Node firstElement; // first element of the bag
14 | private int size; // size of bag
15 |
16 | private static class Node {
17 | private Element content;
18 | private Node nextElement;
19 | }
20 |
21 | /**
22 | * Create an empty bag
23 | */
24 | public Bag() {
25 | firstElement = null;
26 | size = 0;
27 | }
28 |
29 | /**
30 | * @return true if this bag is empty, false otherwise
31 | */
32 | public boolean isEmpty() {
33 | return firstElement == null;
34 | }
35 |
36 | /**
37 | * @return the number of elements
38 | */
39 | public int size() {
40 | return size;
41 | }
42 |
43 | /**
44 | * @param element - the element to add
45 | */
46 | public void add(Element element) {
47 | Node oldfirst = firstElement;
48 | firstElement = new Node<>();
49 | firstElement.content = element;
50 | firstElement.nextElement = oldfirst;
51 | size++;
52 | }
53 |
54 | /**
55 | * Checks if the bag contains a specific element
56 | *
57 | * @param element which you want to look for
58 | * @return true if bag contains element, otherwise false
59 | */
60 | public boolean contains(Element element) {
61 | Iterator iterator = this.iterator();
62 | while(iterator.hasNext()) {
63 | if (iterator.next().equals(element)) {
64 | return true;
65 | }
66 | }
67 | return false;
68 | }
69 |
70 | /**
71 | * @return an iterator that iterates over the elements in this bag in arbitrary order
72 | */
73 | public Iterator iterator() {
74 | return new ListIterator<>(firstElement);
75 | }
76 |
77 | @SuppressWarnings("hiding")
78 | private class ListIterator implements Iterator {
79 | private Node currentElement;
80 |
81 | public ListIterator(Node firstElement) {
82 | currentElement = firstElement;
83 | }
84 |
85 | public boolean hasNext() {
86 | return currentElement != null;
87 | }
88 |
89 | /**
90 | * remove is not allowed in a bag
91 | */
92 | @Override
93 | public void remove() {
94 | throw new UnsupportedOperationException();
95 | }
96 |
97 | public Element next() {
98 | if (!hasNext())
99 | throw new NoSuchElementException();
100 | Element element = currentElement.content;
101 | currentElement = currentElement.nextElement;
102 | return element;
103 | }
104 | }
105 |
106 | /**
107 | * main-method for testing
108 | */
109 | public static void main(String[] args) {
110 | Bag bag = new Bag<>();
111 |
112 | bag.add("1");
113 | bag.add("1");
114 | bag.add("2");
115 |
116 | System.out.println("size of bag = " + bag.size());
117 | for (String s : bag) {
118 | System.out.println(s);
119 | }
120 |
121 | System.out.println(bag.contains(null));
122 | System.out.println(bag.contains("1"));
123 | System.out.println(bag.contains("3"));
124 | }
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/Sorts/QuickSort.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * @author Varun Upadhyay (https://github.com/varunu28)
4 | *
5 | */
6 |
7 | class QuickSort {
8 |
9 | /**
10 | * This method implements the Generic Quick Sort
11 | *
12 | * @param array The array to be sorted
13 | * @param start The first index of an array
14 | * @param end The last index of an array
15 | * Sorts the array in increasing order
16 | **/
17 |
18 | public static > void QS(List list, int left, int right) {
19 | if (left>=right) { return }
20 | else
21 | {
22 | int pivot = partition(array, left,right);
23 | QS(list, left, pivot- 1);
24 | QS(list, pivot + 1, right);
25 | }
26 | }
27 |
28 | /**
29 | * This method finds the partition index for an array
30 | *
31 | * @param array The array to be sorted
32 | * @param start The first index of an array
33 | * @param end The last index of an array
34 | * Finds the partition index of an array
35 | **/
36 |
37 | public static > int partition(List list, int left, int right) {
38 | int mid=(left+right)/2;
39 | T pivot=list.get(mid);
40 | swap(list,mid,right);
41 | while(left=0)
44 | {
45 | ++left;
46 | }
47 | if(left=0)
53 | {
54 | --right;
55 | }
56 | if(left> void swap(List list, int initial, int fin) {
75 | E temp= list.get(initial);
76 | list.set(initial,list.get(fin));
77 | list.set(fin,temp);
78 | }
79 |
80 | // Driver Program
81 | public static void main(String[] args) {
82 |
83 | // For integer input
84 | ArrayList array = new ArrayList(9);
85 | array = {3,4,1,32,0,2,44,111,5};
86 |
87 | QS(array, 0, array.size()-1);
88 |
89 | //Output => 0 1 2 3 4 5 32 44 111
90 | for (int i=0;i array1=new ArrayList(5);
96 | array1 = {"c", "a", "e", "b","d"};
97 |
98 | QS(array1, 0,array1.size()-1);
99 |
100 | //Output => a b c d e
101 | for(int i=0; i=65 && current<= 90)
22 | {
23 | int numAlphabet = message.charAt(i);
24 | if(shift + numAlphabet > 90)
25 | {
26 | int j = 90 - numAlphabet;
27 | char nextKey = (char)(65 + (shift - j - 1));
28 | encoded += nextKey;
29 |
30 | }
31 | else
32 | {
33 | char nextKey = (char)(current + shift);
34 | encoded += nextKey;
35 | }
36 | }
37 | else if (current>=97 && current <= 122)
38 | {
39 | int numAlphabet = message.charAt(i);
40 | if(shift + numAlphabet > 122)
41 | {
42 | int j = 122 - numAlphabet;
43 | char nextKey = (char)(97 + (shift - j - 1));
44 | encoded += nextKey;
45 | }
46 | else
47 | {
48 | char nextKey = (char)(current + shift);
49 | encoded += nextKey;
50 | }
51 | }
52 | }
53 | return encoded;
54 | }
55 | public static String decode (String message,int shift)
56 | {
57 | String decoded = "";
58 | for(int i = 0 ; i=65 && current<= 90)
68 | {
69 | int numAlphabet = message.charAt(i);
70 | if(numAlphabet - shift < 65)
71 | {
72 | int j = numAlphabet - 65;
73 | char nextKey = (char)(90 - (shift - j - 1));
74 | decoded += nextKey;
75 |
76 | }
77 | else
78 | {
79 | char nextKey = (char)(current - shift);
80 | decoded += nextKey;
81 | }
82 | }
83 | else if (current>=97 && current <= 122)
84 | {
85 | int numAlphabet = message.charAt(i);
86 | if(numAlphabet - shift < 97)
87 | {
88 | int j = numAlphabet - 97;
89 | char nextKey = (char)(122 - (shift - j - 1));
90 | decoded += nextKey;
91 | }
92 | else
93 | {
94 | char nextKey = (char)(current - shift);
95 | decoded += nextKey;
96 | }
97 | }
98 | }
99 | return decoded;
100 | }
101 | public static void main(String[] args)
102 | {
103 | Scanner input = new Scanner(System.in);
104 | System.out.println("Please enter the message (Latin Alphabet)");
105 | String message = input.nextLine();
106 | System.out.println(message);
107 | System.out.println("Please enter the shift number");
108 | int shift = input.nextInt() % 26;
109 | System.out.println("(E)ncode or (D)ecode ?");
110 | char choice = input.next().charAt(0);
111 | if(choice == 'E' || choice=='e')
112 | System.out.println("ENCODED MESSAGE IS \n" + encode(message,shift)); //send our function to handle
113 | if(choice =='D' || choice =='d')
114 | System.out.println("DECODED MESSAGE IS \n" + decode(message,shift));
115 | }
116 |
117 | }
--------------------------------------------------------------------------------
/Data Structures/Trees/TreeTraversal.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 |
3 | /**
4 | *
5 | * @author Varun Upadhyay (https://github.com/varunu28)
6 | *
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 3 traversal methods: printInOrder, printPostOrder & printPreOrder
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 | }
61 | else {
62 | left.insert(value);
63 | }
64 | }
65 | else {
66 | if (right == null) {
67 | right = new Node(value);
68 | }
69 | else {
70 | right.insert(value);
71 | }
72 | }
73 | }
74 |
75 | public void printInOrder() {
76 | if (left != null) {
77 | left.printInOrder();
78 | }
79 | System.out.print(data + " ");
80 | if (right != null) {
81 | right.printInOrder();
82 | }
83 | }
84 |
85 | public void printPreOrder() {
86 | System.out.print(data + " ");
87 | if (left != null) {
88 | left.printPreOrder();
89 | }
90 | if (right != null) {
91 | right.printPreOrder();
92 | }
93 | }
94 |
95 | public void printPostOrder() {
96 | if (left != null) {
97 | left.printPostOrder();
98 | }
99 | if (right != null) {
100 | right.printPostOrder();
101 | }
102 | System.out.print(data + " ");
103 | }
104 |
105 | /**
106 | * O(n) time algorithm.
107 | * Uses O(n) space to store nodes in a queue to aid in traversal.
108 | */
109 | public void printLevelOrder() {
110 | LinkedList queue = new LinkedList<>();
111 | queue.add(this);
112 | while (queue.size() > 0) {
113 | Node head = queue.remove();
114 | System.out.print(head.data + " ");
115 | // Add children of recently-printed node to queue, if they exist.
116 | if (head.left != null) {
117 | queue.add(head.left);
118 | }
119 | if (head.right != null) {
120 | queue.add(head.right);
121 | }
122 | }
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/Data Structures/Queues/Queues.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This implements Queues by using the class Queue.
3 | *
4 | * A queue data structure functions the same as a real world queue.
5 | * The elements that are added first are the first to be removed.
6 | * New elements are added to the back/rear of the queue.
7 | *
8 | * @author Unknown
9 | *
10 | */
11 | class Queue{
12 | /** Max size of the queue */
13 | private int maxSize;
14 | /** The array representing the queue */
15 | private int[] queueArray;
16 | /** Front of the queue */
17 | private int front;
18 | /** Rear of the queue */
19 | private int rear;
20 | /** How many items are in the queue */
21 | private int nItems;
22 |
23 | /**
24 | * Constructor
25 | *
26 | * @param size Size of the new queue
27 | */
28 | public Queue(int size){
29 | maxSize = size;
30 | queueArray = new int[size];
31 | front = 0;
32 | rear = -1;
33 | nItems = 0;
34 | }
35 |
36 | /**
37 | * Inserts an element at the rear of the queue
38 | *
39 | * @param x element to be added
40 | * @return True if the element was added successfully
41 | */
42 | public boolean insert(int x){
43 | if(isFull())
44 | return false;
45 | if(rear == maxSize-1) //If the back of the queue is the end of the array wrap around to the front
46 | rear = -1;
47 | rear++;
48 | queueArray[rear] = x;
49 | nItems++;
50 | return true;
51 | }
52 |
53 | /**
54 | * Remove an element from the front of the queue
55 | *
56 | * @return the new front of the queue
57 | */
58 | public int remove(){ //Remove an element from the front of the queue
59 | if(isEmpty()){
60 | System.out.println("Queue is empty");
61 | return -1;
62 | }
63 | int temp = queueArray[front];
64 | front++;
65 | if(front == maxSize) //Dealing with wrap-around again
66 | front = 0;
67 | nItems--;
68 | return temp;
69 | }
70 |
71 | /**
72 | * Checks what's at the front of the queue
73 | *
74 | * @return element at the front of the queue
75 | */
76 | public int peekFront(){
77 | return queueArray[front];
78 | }
79 |
80 | /**
81 | * Checks what's at the rear of the queue
82 | *
83 | * @return element at the rear of the queue
84 | */
85 | public int peekRear(){
86 | return queueArray[rear];
87 | }
88 |
89 | /**
90 | * Returns true if the queue is empty
91 | *
92 | * @return true if the queue is empty
93 | */
94 | public boolean isEmpty(){
95 | return(nItems == 0);
96 | }
97 |
98 | /**
99 | * Returns true if the queue is full
100 | *
101 | * @return true if the queue is full
102 | */
103 | public boolean isFull(){
104 | return(nItems == maxSize);
105 | }
106 |
107 | /**
108 | * Returns the number of elements in the queue
109 | *
110 | * @return number of elements in the queue
111 | */
112 | public int getSize(){
113 | return nItems;
114 | }
115 | }
116 |
117 | /**
118 | * This class is the example for the Queue class
119 | *
120 | * @author Unknown
121 | *
122 | */
123 | public class Queues{
124 | /**
125 | * Main method
126 | *
127 | * @param args Command line arguments
128 | */
129 | public static void main(String args[]){
130 | Queue myQueue = new Queue(4);
131 | myQueue.insert(10);
132 | myQueue.insert(2);
133 | myQueue.insert(5);
134 | myQueue.insert(3);
135 | //[10(front), 2, 5, 3(rear)]
136 |
137 | System.out.println(myQueue.isFull()); //Will print true
138 |
139 | myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue
140 | //[10, 2(front), 5, 3(rear)]
141 |
142 | myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around
143 | // [7(rear), 2(front), 5, 3]
144 |
145 | System.out.println(myQueue.peekFront()); //Will print 2
146 | System.out.println(myQueue.peekRear()); //Will print 7
147 | }
148 | }
--------------------------------------------------------------------------------
/Data Structures/Lists/SinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This class implements a SinglyLinked List. This is done
3 | * using SinglyLinkedList class and a LinkForLinkedList Class.
4 | *
5 | * A linked list is implar to an array, it hold values.
6 | * However, links in a linked list do not have indexes. With
7 | * a linked list you do not need to predetermine it's size as
8 | * it gorws and shrinks as it is edited. This is an example of
9 | * a singly linked list. Elements can only be added/removed
10 | * at the head/front of the list.
11 | *
12 | * @author Unknown
13 | *
14 | */
15 | class SinglyLinkedList{
16 | /**Head refered to the front of the list */
17 | private Node head;
18 |
19 | /**
20 | * Constructor of SinglyLinkedList
21 | */
22 | public SinglyLinkedList(){
23 | head = null;
24 | }
25 |
26 | /**
27 | * This method inserts an element at the head
28 | *
29 | * @param x Element to be added
30 | */
31 | public void insertHead(int x){
32 | Node newNode = new Node(x); //Create a new link with a value attached to it
33 | newNode.next = head; //Set the new link to point to the current head
34 | head = newNode; //Now set the new link to be the head
35 | }
36 |
37 |
38 | /**
39 | * Inserts a new node at a specified position
40 | * @param head head node of the linked list
41 | * @param data data to be stored in a new node
42 | * @param position position at which a new node is to be inserted
43 | * @return reference of the head of the linked list
44 | */
45 |
46 | Node InsertNth(Node head, int data, int position) {
47 |
48 | Node newNode = new Node();
49 | newNode.data = data;
50 |
51 | if (position == 0) {
52 | newNode.next = head;
53 | return newNode;
54 | }
55 |
56 | Node current = head;
57 |
58 | while (--position > 0) {
59 | current = current.next;
60 | }
61 |
62 | newNode.next = current.next;
63 | current.next = newNode;
64 | return head;
65 | }
66 |
67 | /**
68 | * This method deletes an element at the head
69 | *
70 | * @return The element deleted
71 | */
72 | public Node deleteHead(){
73 | Node temp = head;
74 | head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
75 | return temp;
76 | }
77 |
78 | /**
79 | * Checks if the list is empty
80 | *
81 | * @return true is list is empty
82 | */
83 | public boolean isEmpty(){
84 | return(head == null);
85 | }
86 |
87 | /**
88 | * Prints contents of the list
89 | */
90 | public void display(){
91 | Node current = head;
92 | while(current!=null){
93 | System.out.print(current.getValue()+" ");
94 | current = current.next;
95 | }
96 | System.out.println();
97 | }
98 |
99 | /**
100 | * Main method
101 | *
102 | * @param args Command line arguments
103 | */
104 | public static void main(String args[]){
105 | SinglyLinkedList myList = new SinglyLinkedList();
106 |
107 | System.out.println(myList.isEmpty()); //Will print true
108 |
109 | myList.insertHead(5);
110 | myList.insertHead(7);
111 | myList.insertHead(10);
112 |
113 | myList.display(); // 10(head) --> 7 --> 5
114 |
115 | myList.deleteHead();
116 |
117 | myList.display(); // 7(head) --> 5
118 | }
119 | }
120 |
121 | /**
122 | * This class is the nodes of the SinglyLinked List.
123 | * They consist of a vlue and a pointer to the node
124 | * after them.
125 | *
126 | * @author Unknown
127 | *
128 | */
129 | class Node{
130 | /** The value of the node */
131 | public int value;
132 | /** Point to the next node */
133 | public Node next; //This is what the link will point to
134 |
135 | /**
136 | * Constructor
137 | *
138 | * @param valuein Value to be put in the node
139 | */
140 | public Node(int valuein){
141 | value = valuein;
142 | }
143 |
144 | /**
145 | * Returns value of the node
146 | */
147 | public int getValue(){
148 | return value;
149 | }
150 |
151 | }
152 |
--------------------------------------------------------------------------------
/Data Structures/Graphs/PrimMST.java:
--------------------------------------------------------------------------------
1 | // A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
2 | //adjacency matrix representation of the graph
3 |
4 | import java.lang.*;
5 |
6 | class PrimMST
7 | {
8 | // Number of vertices in the graph
9 | private static final int V=5;
10 |
11 | // A utility function to find the vertex with minimum key
12 | // value, from the set of vertices not yet included in MST
13 | int minKey(int key[], Boolean mstSet[])
14 | {
15 | // Initialize min value
16 | int min = Integer.MAX_VALUE, min_index=-1;
17 |
18 | for (int v = 0; v < V; v++)
19 | if (mstSet[v] == false && key[v] < min)
20 | {
21 | min = key[v];
22 | min_index = v;
23 | }
24 |
25 | return min_index;
26 | }
27 |
28 | // A utility function to print the constructed MST stored in
29 | // parent[]
30 | void printMST(int parent[], int n, int graph[][])
31 | {
32 | System.out.println("Edge Weight");
33 | for (int i = 1; i < V; i++)
34 | System.out.println(parent[i]+" - "+ i+" "+
35 | graph[i][parent[i]]);
36 | }
37 |
38 | // Function to construct and print MST for a graph represented
39 | // using adjacency matrix representation
40 | void primMST(int graph[][])
41 | {
42 | // Array to store constructed MST
43 | int parent[] = new int[V];
44 |
45 | // Key values used to pick minimum weight edge in cut
46 | int key[] = new int [V];
47 |
48 | // To represent set of vertices not yet included in MST
49 | Boolean mstSet[] = new Boolean[V];
50 |
51 | // Initialize all keys as INFINITE
52 | for (int i = 0; i < V; i++)
53 | {
54 | key[i] = Integer.MAX_VALUE;
55 | mstSet[i] = false;
56 | }
57 |
58 | // Always include first 1st vertex in MST.
59 | key[0] = 0; // Make key 0 so that this vertex is
60 | // picked as first vertex
61 | parent[0] = -1; // First node is always root of MST
62 |
63 | // The MST will have V vertices
64 | for (int count = 0; count < V-1; count++)
65 | {
66 | // Pick thd minimum key vertex from the set of vertices
67 | // not yet included in MST
68 | int u = minKey(key, mstSet);
69 |
70 | // Add the picked vertex to the MST Set
71 | mstSet[u] = true;
72 |
73 | // Update key value and parent index of the adjacent
74 | // vertices of the picked vertex. Consider only those
75 | // vertices which are not yet included in MST
76 | for (int v = 0; v < V; v++)
77 |
78 | // graph[u][v] is non zero only for adjacent vertices of m
79 | // mstSet[v] is false for vertices not yet included in MST
80 | // Update the key only if graph[u][v] is smaller than key[v]
81 | if (graph[u][v]!=0 && mstSet[v] == false &&
82 | graph[u][v] < key[v])
83 | {
84 | parent[v] = u;
85 | key[v] = graph[u][v];
86 | }
87 | }
88 |
89 | // print the constructed MST
90 | printMST(parent, V, graph);
91 | }
92 |
93 | public static void main (String[] args)
94 | {
95 | /* Let us create the following graph
96 | 2 3
97 | (0)--(1)--(2)
98 | | / \ |
99 | 6| 8/ \5 |7
100 | | / \ |
101 | (3)-------(4)
102 | 9 */
103 | PrimMST t = new PrimMST();
104 | int graph[][] = new int[][] {{0, 2, 0, 6, 0},
105 | {2, 0, 3, 8, 5},
106 | {0, 3, 0, 0, 7},
107 | {6, 8, 0, 0, 9},
108 | {0, 5, 7, 9, 0},
109 | };
110 |
111 | // Print the solution
112 | t.primMST(graph);
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/Data Structures/Heaps/HeapElement.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package heaps;
5 |
6 | import java.lang.Double;
7 | import java.lang.Object;
8 |
9 | /**
10 | * Class for heap elements.
11 | * A heap element contains two attributes: a key which will be used to build the tree (int
12 | * or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit
13 | * to carry any information he/she likes. Be aware that the use of a mutable object might
14 | * jeopardize the integrity of this information.
15 | * @author Nicolas Renard
16 | *
17 | */
18 | public class HeapElement {
19 | private final double key;
20 | private final Object additionalInfo;
21 |
22 | // Constructors
23 |
24 | /**
25 | *
26 | * @param key : a number of primitive type 'double'
27 | * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
28 | * additional information of use for the user
29 | */
30 | public HeapElement(double key, Object info) {
31 | this.key = key;
32 | this.additionalInfo = info;
33 | }
34 |
35 | /**
36 | *
37 | * @param key : a number of primitive type 'int'
38 | * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
39 | * additional information of use for the user
40 | */
41 | public HeapElement(int key, Object info) {
42 | this.key = key;
43 | this.additionalInfo = info;
44 | }
45 |
46 | /**
47 | *
48 | * @param key : a number of object type 'Integer'
49 | * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
50 | * additional information of use for the user
51 | */
52 | public HeapElement(Integer key, Object info) {
53 | this.key = key;
54 | this.additionalInfo = info;
55 | }
56 |
57 | /**
58 | *
59 | * @param key : a number of object type 'Double'
60 | * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
61 | * additional information of use for the user
62 | */
63 | public HeapElement(Double key, Object info) {
64 | this.key = key;
65 | this.additionalInfo = info;
66 | }
67 |
68 | /**
69 | *
70 | * @param key : a number of primitive type 'double'
71 | */
72 | public HeapElement(double key) {
73 | this.key = key;
74 | this.additionalInfo = null;
75 | }
76 |
77 | /**
78 | *
79 | * @param key : a number of primitive type 'int'
80 | */
81 | public HeapElement(int key) {
82 | this.key = key;
83 | this.additionalInfo = null;
84 | }
85 |
86 | /**
87 | *
88 | * @param key : a number of object type 'Integer'
89 | */
90 | public HeapElement(Integer key) {
91 | this.key = key;
92 | this.additionalInfo = null;
93 | }
94 |
95 | /**
96 | *
97 | * @param key : a number of object type 'Double'
98 | */
99 | public HeapElement(Double key) {
100 | this.key = key;
101 | this.additionalInfo = null;
102 | }
103 |
104 | // Getters
105 | /**
106 | * @return the object containing the additional info provided by the user.
107 | */
108 | public Object getInfo() {
109 | return additionalInfo;
110 | }
111 | /**
112 | * @return the key value of the element
113 | */
114 | public double getKey() {
115 | return key;
116 | }
117 |
118 | // Overridden object methods
119 |
120 | public String toString() {
121 | return "Key: " + key + " - " +additionalInfo.toString();
122 | }
123 | /**
124 | *
125 | * @param otherHeapElement
126 | * @return true if the keys on both elements are identical and the additional info objects
127 | * are identical.
128 | */
129 | public boolean equals(HeapElement otherHeapElement) {
130 | return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/Data Structures/Buffers/CircularBuffer.java:
--------------------------------------------------------------------------------
1 | import java.util.Random;
2 | import java.util.concurrent.atomic.AtomicInteger;
3 |
4 | public class CircularBuffer {
5 | private char[] _buffer;
6 | public final int _buffer_size;
7 | private int _write_index = 0;
8 | private int _read_index = 0;
9 | private AtomicInteger _readable_data = new AtomicInteger(0);
10 |
11 | public CircularBuffer(int buffer_size) {
12 | if(!IsPowerOfTwo(buffer_size)) {
13 | throw new IllegalArgumentException();
14 | }
15 | this._buffer_size = buffer_size;
16 | _buffer = new char[buffer_size];
17 | }
18 |
19 | private boolean IsPowerOfTwo(int i) {
20 | return (i & (i - 1)) == 0;
21 | }
22 |
23 | private int getTrueIndex(int i) {
24 | return i % _buffer_size;
25 | }
26 |
27 | public Character readOutChar() {
28 | Character result = null;
29 |
30 | //if we have data to read
31 | if(_readable_data.get() > 0) {
32 | result = new Character(_buffer[getTrueIndex(_read_index)]);
33 | _readable_data.decrementAndGet();
34 | _read_index++;
35 | }
36 |
37 | return result;
38 | }
39 |
40 | public boolean writeToCharBuffer(char c) {
41 | boolean result = false;
42 |
43 | //if we can write to the buffer
44 | if(_readable_data.get() < _buffer_size) {
45 | //write to buffer
46 | _buffer[getTrueIndex(_write_index)] = c;
47 | _readable_data.incrementAndGet();
48 | _write_index++;
49 | result = true;
50 | }
51 |
52 | return result;
53 | }
54 |
55 | private static class TestWriteWorker implements Runnable {
56 | String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
57 | Random _random = new Random();
58 | CircularBuffer _buffer;
59 | public TestWriteWorker(CircularBuffer cb) {
60 | this._buffer = cb;
61 | }
62 |
63 | private char getRandomChar() {
64 | return _alphabet.charAt(_random.nextInt(_alphabet.length()));
65 | }
66 |
67 | public void run() {
68 | while(!Thread.interrupted()) {
69 | if(!_buffer.writeToCharBuffer(getRandomChar())){
70 | Thread.yield();
71 | try{
72 | Thread.sleep(10);
73 | } catch (InterruptedException e) {
74 | return;
75 | }
76 | }
77 | }
78 | }
79 | }
80 |
81 | private static class TestReadWorker implements Runnable {
82 | CircularBuffer _buffer;
83 | public TestReadWorker(CircularBuffer cb) {
84 | this._buffer = cb;
85 | }
86 |
87 | public void run() {
88 | System.out.println("Printing Buffer:");
89 | while(!Thread.interrupted()) {
90 | Character c = _buffer.readOutChar();
91 | if(c != null) {
92 | System.out.print(c.charValue());
93 | } else {
94 | Thread.yield();
95 | try {
96 | Thread.sleep(10);
97 | } catch (InterruptedException e) {
98 | System.out.println();
99 | return;
100 | }
101 | }
102 | }
103 | }
104 | }
105 |
106 | public static void main(String[] args) throws InterruptedException {
107 | int buffer_size = 1024;
108 | //create circular buffer
109 | CircularBuffer cb = new CircularBuffer(buffer_size);
110 |
111 | //create threads that read and write the buffer.
112 | Thread write_thread = new Thread(new TestWriteWorker(cb));
113 | Thread read_thread = new Thread(new TestReadWorker(cb));
114 | read_thread.start();
115 | write_thread.start();
116 |
117 | //wait some amount of time
118 | Thread.sleep(10000);
119 |
120 | //interrupt threads and exit
121 | write_thread.interrupt();
122 | read_thread.interrupt();
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/Others/QueueUsingTwoStacks.java:
--------------------------------------------------------------------------------
1 | import java.util.Stack;
2 |
3 | /**
4 | * This implements Queue using two Stacks.
5 | *
6 | * Big O Runtime:
7 | * insert(): O(1)
8 | * remove(): O(1) amortized
9 | * isEmpty(): O(1)
10 | *
11 | * A queue data structure functions the same as a real world queue.
12 | * The elements that are added first are the first to be removed.
13 | * New elements are added to the back/rear of the queue.
14 | *
15 | * @author sahilb2
16 | *
17 | */
18 | class QueueWithStack {
19 |
20 | // Stack to keep track of elements inserted into the queue
21 | private Stack inStack;
22 | // Stack to keep track of elements to be removed next in queue
23 | private Stack outStack;
24 |
25 | /**
26 | * Constructor
27 | */
28 | public QueueWithStack() {
29 | this.inStack = new Stack();
30 | this.outStack = new Stack();
31 | }
32 |
33 | /**
34 | * Inserts an element at the rear of the queue
35 | *
36 | * @param x element to be added
37 | */
38 | public void insert(Object x) {
39 | // Insert element into inStack
40 | this.inStack.push(x);
41 | }
42 |
43 | /**
44 | * Remove an element from the front of the queue
45 | *
46 | * @return the new front of the queue
47 | */
48 | public Object remove() {
49 | if(this.outStack.isEmpty()) {
50 | // Move all elements from inStack to outStack (preserving the order)
51 | while(!this.inStack.isEmpty()) {
52 | this.outStack.push( this.inStack.pop() );
53 | }
54 | }
55 | return this.outStack.pop();
56 | }
57 |
58 | /**
59 | * Peek at the element from the front of the queue
60 | *
61 | * @return the new front of the queue
62 | */
63 | public Object peek() {
64 | if(this.outStack.isEmpty()) {
65 | // Move all elements from inStack to outStack (preserving the order)
66 | while(!this.inStack.isEmpty()) {
67 | this.outStack.push( this.inStack.pop() );
68 | }
69 | }
70 | return this.outStack.peek();
71 | }
72 |
73 | /**
74 | * Returns true if the queue is empty
75 | *
76 | * @return true if the queue is empty
77 | */
78 | public boolean isEmpty() {
79 | return (this.inStack.isEmpty() && this.outStack.isEmpty());
80 | }
81 |
82 | }
83 |
84 | /**
85 | * This class is the example for the Queue class
86 | *
87 | * @author sahilb2
88 | *
89 | */
90 | public class QueueUsingTwoStacks {
91 |
92 | /**
93 | * Main method
94 | *
95 | * @param args Command line arguments
96 | */
97 | public static void main(String args[]){
98 | QueueWithStack myQueue = new QueueWithStack();
99 | myQueue.insert(1);
100 | // instack: [(top) 1]
101 | // outStack: []
102 | myQueue.insert(2);
103 | // instack: [(top) 2, 1]
104 | // outStack: []
105 | myQueue.insert(3);
106 | // instack: [(top) 3, 2, 1]
107 | // outStack: []
108 | myQueue.insert(4);
109 | // instack: [(top) 4, 3, 2, 1]
110 | // outStack: []
111 |
112 | System.out.println(myQueue.isEmpty()); //Will print false
113 |
114 | System.out.println(myQueue.remove()); //Will print 1
115 | // instack: []
116 | // outStack: [(top) 2, 3, 4]
117 |
118 | myQueue.insert(5);
119 | System.out.println(myQueue.peek()); //Will print 2
120 | // instack: [(top) 5]
121 | // outStack: [(top) 2, 3, 4]
122 |
123 | myQueue.remove();
124 | System.out.println(myQueue.peek()); //Will print 3
125 | // instack: [(top) 5]
126 | // outStack: [(top) 3, 4]
127 | myQueue.remove();
128 | System.out.println(myQueue.peek()); //Will print 4
129 | // instack: [(top) 5]
130 | // outStack: [(top) 4]
131 | myQueue.remove();
132 | // instack: [(top) 5]
133 | // outStack: []
134 | System.out.println(myQueue.peek()); //Will print 5
135 | // instack: []
136 | // outStack: [(top) 5]
137 | myQueue.remove();
138 | // instack: []
139 | // outStack: []
140 |
141 | System.out.println(myQueue.isEmpty()); //Will print true
142 |
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/Data Structures/Graphs/MatrixGraphs.java:
--------------------------------------------------------------------------------
1 | public class MatrixGraphs {
2 |
3 | public static void main(String args[]) {
4 | AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
5 | graph.addEdge(1, 2);
6 | graph.addEdge(1, 5);
7 | graph.addEdge(2, 5);
8 | graph.addEdge(1, 2);
9 | graph.addEdge(2, 3);
10 | graph.addEdge(3, 4);
11 | graph.addEdge(4, 1);
12 | graph.addEdge(2, 3);
13 | System.out.println(graph);
14 | }
15 |
16 | }
17 |
18 | class AdjacencyMatrixGraph {
19 | private int _numberOfVertices;
20 | private int _numberOfEdges;
21 | private int[][] _adjacency;
22 |
23 | static final int EDGE_EXIST = 1;
24 | static final int EDGE_NONE = 0;
25 |
26 | public AdjacencyMatrixGraph(int givenNumberOfVertices) {
27 | this.setNumberOfVertices(givenNumberOfVertices);
28 | this.setNumberOfEdges(0);
29 | this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
30 | for (int i = 0; i < givenNumberOfVertices; i++) {
31 | for (int j = 0; j < givenNumberOfVertices; j++) {
32 | this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
33 | }
34 | }
35 | }
36 |
37 | private void setNumberOfVertices(int newNumberOfVertices) {
38 | this._numberOfVertices = newNumberOfVertices;
39 | }
40 |
41 | public int numberOfVertices() {
42 | return this._numberOfVertices;
43 | }
44 |
45 | private void setNumberOfEdges(int newNumberOfEdges) {
46 | this._numberOfEdges = newNumberOfEdges;
47 | }
48 |
49 | public int numberOfEdges() {
50 | return this._numberOfEdges;
51 | }
52 |
53 | private void setAdjacency(int[][] newAdjacency) {
54 | this._adjacency = newAdjacency;
55 | }
56 |
57 | private int[][] adjacency() {
58 | return this._adjacency;
59 | }
60 |
61 | private boolean adjacencyOfEdgeDoesExist(int from, int to) {
62 | return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE);
63 | }
64 |
65 | public boolean vertexDoesExist(int aVertex) {
66 | if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
67 | return true;
68 | } else {
69 | return false;
70 | }
71 | }
72 |
73 | public boolean edgeDoesExist(int from, int to) {
74 | if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
75 | return (this.adjacencyOfEdgeDoesExist(from, to));
76 | }
77 |
78 | return false;
79 | }
80 |
81 | /**
82 | * This method adds an edge to the graph between two specified
83 | * vertices
84 | *
85 | * @param from the data of the vertex the edge is from
86 | * @param to the data of the vertex the edge is going to
87 | * @return returns true if the edge did not exist, return false if it already did
88 | */
89 | public boolean addEdge(int from, int to) {
90 | if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
91 | if (!this.adjacencyOfEdgeDoesExist(from, to)) {
92 | this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST;
93 | this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST;
94 | this.setNumberOfEdges(this.numberOfEdges() + 1);
95 | return true;
96 | }
97 | }
98 |
99 | return false;
100 | }
101 |
102 | /**
103 | * this method removes an edge from the graph between two specified
104 | * vertices
105 | *
106 | * @param from the data of the vertex the edge is from
107 | * @param to the data of the vertex the edge is going to
108 | * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
109 | */
110 | public boolean removeEdge(int from, int to) {
111 | if(!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
112 | if (this.adjacencyOfEdgeDoesExist(from, to)) {
113 | this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
114 | this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;
115 | this.setNumberOfEdges(this.numberOfEdges() - 1);
116 | return true;
117 | }
118 | }
119 | return false;
120 | }
121 |
122 | /**
123 | * this gives a list of vertices in the graph and their adjacencies
124 | *
125 | * @return returns a string describing this graph
126 | */
127 | public String toString() {
128 | String s = new String();
129 | s = " ";
130 | for (int i = 0; i < this.numberOfVertices(); i++) {
131 | s = s + String.valueOf(i) + " ";
132 | }
133 | s = s + " \n";
134 |
135 | for (int i = 0; i < this.numberOfVertices(); i++) {
136 | s = s + String.valueOf(i) + " : ";
137 | for (int j = 0; j < this.numberOfVertices(); j++) {
138 | s = s + String.valueOf(this._adjacency[i][j]) + " ";
139 | }
140 | s = s + "\n";
141 | }
142 | return s;
143 | }
144 |
145 | }
146 |
--------------------------------------------------------------------------------
/Data Structures/Graphs/Graphs.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.lang.StringBuilder;
3 |
4 | class AdjacencyListGraph> {
5 |
6 | ArrayList verticies;
7 |
8 | public AdjacencyListGraph() {
9 | verticies = new ArrayList<>();
10 | }
11 |
12 | private class Vertex {
13 | E data;
14 | ArrayList adjacentVerticies;
15 |
16 | public Vertex(E data) {
17 | adjacentVerticies = new ArrayList<>();
18 | this.data = data;
19 | }
20 |
21 | public boolean addAdjacentVertex(Vertex to) {
22 | for (Vertex v: adjacentVerticies) {
23 | if (v.data.compareTo(to.data) == 0) {
24 | return false; // the edge already exists
25 | }
26 | }
27 | return adjacentVerticies.add(to); // this will return true;
28 | }
29 |
30 | public boolean removeAdjacentVertex(E to) {
31 | // use indexes here so it is possible to
32 | // remove easily without implementing
33 | // equals method that ArrayList.remove(Object o) uses
34 | for (int i = 0; i < adjacentVerticies.size(); i++) {
35 | if (adjacentVerticies.get(i).data.compareTo(to) == 0) {
36 | adjacentVerticies.remove(i);
37 | return true;
38 | }
39 | }
40 | return false;
41 | }
42 | }
43 |
44 | /**
45 | * this method removes an edge from the graph between two specified
46 | * verticies
47 | *
48 | * @param from the data of the vertex the edge is from
49 | * @param to the data of the vertex the edge is going to
50 | * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
51 | */
52 | public boolean removeEdge(E from, E to) {
53 | Vertex fromV = null;
54 | for (Vertex v: verticies) {
55 | if (from.compareTo(v.data) == 0) {
56 | fromV = v;
57 | break;
58 | }
59 | }
60 | if (fromV == null) return false;
61 | return fromV.removeAdjacentVertex(to);
62 | }
63 | /**
64 | * this method adds an edge to the graph between two specified
65 | * verticies
66 | *
67 | * @param from the data of the vertex the edge is from
68 | * @param to the data of the vertex the edge is going to
69 | * @return returns true if the edge did not exist, return false if it already did
70 | */
71 | public boolean addEdge(E from, E to) {
72 | Vertex fromV = null, toV = null;
73 | for (Vertex v: verticies) {
74 | if (from.compareTo(v.data) == 0) { // see if from vertex already exists
75 | fromV = v;
76 | } else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
77 | toV = v;
78 | }
79 | if (fromV != null && toV != null) break; // both nodes exist so stop searching
80 | }
81 | if (fromV == null) {
82 | fromV = new Vertex(from);
83 | verticies.add(fromV);
84 | }
85 | if (toV == null) {
86 | toV = new Vertex(to);
87 | verticies.add(toV);
88 | }
89 | return fromV.addAdjacentVertex(toV);
90 | }
91 |
92 | /**
93 | * this gives a list of verticies in the graph and their adjacencies
94 | *
95 | * @return returns a string describing this graph
96 | */
97 | public String toString() {
98 | StringBuilder sb = new StringBuilder();
99 | for (Vertex v: verticies) {
100 | sb.append("Vertex: ");
101 | sb.append(v.data);
102 | sb.append("\n");
103 | sb.append("Adjacent verticies: ");
104 | for (Vertex v2: v.adjacentVerticies) {
105 | sb.append(v2.data);
106 | sb.append(" ");
107 | }
108 | sb.append("\n");
109 | }
110 | return sb.toString();
111 | }
112 | }
113 |
114 | public class Graphs {
115 |
116 | public static void main(String args[]) {
117 | AdjacencyListGraph graph = new AdjacencyListGraph<>();
118 | assert graph.addEdge(1, 2);
119 | assert graph.addEdge(1, 5);
120 | assert graph.addEdge(2, 5);
121 | assert !graph.addEdge(1, 2);
122 | assert graph.addEdge(2, 3);
123 | assert graph.addEdge(3, 4);
124 | assert graph.addEdge(4, 1);
125 | assert !graph.addEdge(2, 3);
126 | System.out.println(graph);
127 | }
128 |
129 | }
130 |
--------------------------------------------------------------------------------
/Data Structures/Trees/TrieImp.java:
--------------------------------------------------------------------------------
1 | //Trie Data structure implementation without any libraries */
2 |
3 | /**
4 | *
5 | * @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
6 | *
7 | */
8 | import java.util.Scanner;
9 |
10 | public class TrieImp {
11 |
12 | public class TrieNode {
13 | TrieNode[] child;
14 | boolean end;
15 |
16 | public TrieNode(){
17 | child = new TrieNode[26];
18 | end = false;
19 | }
20 | }
21 | private final TrieNode root;
22 | public TrieImp(){
23 | root = new TrieNode();
24 | }
25 |
26 | public void insert(String word){
27 | TrieNode currentNode = root;
28 | for(int i=0; i < word.length();i++){
29 | TrieNode node = currentNode.child[word.charAt(i)-'a'];
30 | if(node == null){
31 | node = new TrieNode();
32 | currentNode.child[word.charAt(i)-'a']=node;
33 | }
34 | currentNode = node;
35 | }
36 | currentNode.end = true;
37 | }
38 | public boolean search(String word){
39 | TrieNode currentNode = root;
40 | for(int i=0;i MAXIMUM_BASE || b1 < MINIMUM_BASE) {
33 | System.out.println("Invalid base!");
34 | continue;
35 | }
36 | if (!validForBase(n, b1)) {
37 | System.out.println("The number is invalid for this base!");
38 | continue;
39 | }
40 | System.out.print("Enter end base (between "+MINIMUM_BASE+" and "+MAXIMUM_BASE+"): ");
41 | b2 = in.nextInt();
42 | if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
43 | System.out.println("Invalid base!");
44 | continue;
45 | }
46 | break;
47 | } catch (InputMismatchException e) {
48 | System.out.println("Invalid input.");
49 | in.next();
50 | }
51 | }
52 | System.out.println(base2base(n, b1, b2));
53 | }
54 |
55 | /**
56 | * Checks if a number (as a String) is valid for a given base.
57 | */
58 | public static boolean validForBase(String n, int base) {
59 | char[] validDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
60 | 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
61 | 'W', 'X', 'Y', 'Z'};
62 | // digitsForBase contains all the valid digits for the base given
63 | char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base);
64 |
65 | // Convert character array into set for convenience of contains() method
66 | HashSet digitsList = new HashSet();
67 | for (int i=0; i9 and store it in charB2
98 | if (charB1 >= 'A' && charB1 <= 'Z')
99 | charB2 = 10 + (charB1 - 'A');
100 | // Else, store the integer value in charB2
101 | else
102 | charB2 = charB1 - '0';
103 | // Convert the digit to decimal and add it to the
104 | // decimalValue of n
105 | decimalValue = decimalValue * b1 + charB2;
106 | }
107 |
108 | // Converting the decimal value to base b2:
109 | // A number is converted from decimal to another base
110 | // by continuously dividing by the base and recording
111 | // the remainder until the quotient is zero. The number in the
112 | // new base is the remainders, with the last remainder
113 | // being the left-most digit.
114 |
115 | // While the quotient is NOT zero:
116 | while (decimalValue != 0) {
117 | // If the remainder is a digit < 10, simply add it to
118 | // the left side of the new number.
119 | if (decimalValue % b2 < 10)
120 | output = Integer.toString(decimalValue % b2) + output;
121 | // If the remainder is >= 10, add a character with the
122 | // corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
123 | else
124 | output = (char)((decimalValue % b2)+55) + output;
125 | // Divide by the new base again
126 | decimalValue /= b2;
127 | }
128 | return output;
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/Data Structures/Stacks/NodeStack.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Implementation of a stack using nodes.
3 | * Unlimited size, no arraylist.
4 | *
5 | * @author Kyler Smith, 2017
6 | */
7 |
8 |
9 | public class NodeStack- {
10 |
11 | /**
12 | * Entry point for the program.
13 | */
14 | public static void main(String[] args) {
15 | NodeStack Stack = new NodeStack();
16 |
17 | Stack.push(3);
18 | Stack.push(4);
19 | Stack.push(5);
20 | System.out.println("Testing :");
21 | Stack.print(); // prints : 5 4 3
22 |
23 | Integer x = Stack.pop(); // x = 5
24 | Stack.push(1);
25 | Stack.push(8);
26 | Integer y = Stack.peek(); // y = 8
27 | System.out.println("Testing :");
28 | Stack.print(); // prints : 8 1 4 3
29 |
30 | System.out.println("Testing :");
31 | System.out.println("x : " + x);
32 | System.out.println("y : " + y);
33 | }
34 |
35 | /**
36 | * Information each node should contain.
37 | * @value data : information of the value in the node
38 | * @value head : the head of the stack
39 | * @value next : the next value from this node
40 | * @value previous : the last value from this node
41 | * @value size : size of the stack
42 | */
43 | private Item data;
44 | private static NodeStack> head;
45 | private NodeStack> next;
46 | private NodeStack> previous;
47 | private static int size = 0;
48 |
49 |
50 | /**
51 | * Constructors for the NodeStack.
52 | */
53 | public NodeStack() {
54 | }
55 |
56 | private NodeStack(Item item) {
57 | this.data = item;
58 | }
59 |
60 | /**
61 | * Put a value onto the stack.
62 | *
63 | * @param item : value to be put on the stack.
64 | */
65 | public void push(Item item) {
66 |
67 | NodeStack
- newNs = new NodeStack
- (item);
68 |
69 | if(this.isEmpty()) {
70 | NodeStack.setHead(new NodeStack<>(item));
71 | newNs.setNext(null);
72 | newNs.setPrevious(null);
73 | } else {
74 | newNs.setPrevious(NodeStack.head);
75 | NodeStack.head.setNext(newNs);
76 | NodeStack.head = newNs;
77 | }
78 |
79 | NodeStack.setSize(NodeStack.getSize() + 1);
80 | }
81 |
82 | /**
83 | * Value to be taken off the stack.
84 | *
85 | * @return item : value that is returned.
86 | */
87 | public Item pop() {
88 |
89 | Item item = (Item) NodeStack.head.getData();
90 |
91 | NodeStack.head = NodeStack.head.getPrevious();
92 | NodeStack.head.setNext(null);
93 |
94 | NodeStack.setSize(NodeStack.getSize() - 1);
95 |
96 | return item;
97 | }
98 |
99 | /**
100 | * Value that is next to be taken off the stack.
101 | *
102 | * @return item : the next value that would be popped off the stack.
103 | */
104 | public Item peek() {
105 | return (Item) NodeStack.head.getData();
106 | }
107 |
108 | /**
109 | * If the stack is empty or there is a value in.
110 | *
111 | * @return boolean : whether or not the stack has anything in it.
112 | */
113 | public boolean isEmpty() {
114 | return NodeStack.getSize() == 0;
115 | }
116 |
117 | /**
118 | * Returns the size of the stack.
119 | *
120 | * @return int : number of values in the stack.
121 | */
122 | public int size() {
123 | return NodeStack.getSize();
124 | }
125 |
126 | /**
127 | * Print the contents of the stack in the following format.
128 | *
129 | * x <- head (next out)
130 | * y
131 | * z <- tail (first in)
132 | * .
133 | * .
134 | * .
135 | *
136 | */
137 | public void print() {
138 | for(NodeStack> n = NodeStack.head; n != null; n = n.previous) {
139 | System.out.println(n.getData().toString());
140 | }
141 | }
142 |
143 | /** Getters and setters (private) */
144 | private NodeStack> getHead() {
145 | return NodeStack.head;
146 | }
147 |
148 | private static void setHead(NodeStack> ns) {
149 | NodeStack.head = ns;
150 | }
151 |
152 | private NodeStack> getNext() {
153 | return next;
154 | }
155 |
156 | private void setNext(NodeStack> next) {
157 | this.next = next;
158 | }
159 |
160 | private NodeStack> getPrevious() {
161 | return previous;
162 | }
163 |
164 | private void setPrevious(NodeStack> previous) {
165 | this.previous = previous;
166 | }
167 |
168 | private static int getSize() {
169 | return size;
170 | }
171 |
172 | private static void setSize(int size) {
173 | NodeStack.size = size;
174 | }
175 |
176 | private Item getData() {
177 | return this.data;
178 | }
179 |
180 | private void setData(Item item) {
181 | this.data = item;
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/Data Structures/Heaps/MaxHeap.java:
--------------------------------------------------------------------------------
1 | package heaps;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
8 | * to its children's.
9 | * @author Nicolas Renard
10 | *
11 | */
12 | public class MaxHeap implements Heap {
13 |
14 | private final List maxHeap;
15 |
16 | public MaxHeap(List listElements) throws Exception {
17 | maxHeap = new ArrayList();
18 | for (HeapElement heapElement : listElements) {
19 | if (heapElement != null) insertElement(heapElement);
20 | else System.out.println("Null element. Not added to heap");
21 | }
22 | if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap.");
23 | }
24 |
25 | // Get the element at a given index. The key for the list is equal to index value - 1
26 | public HeapElement getElement(int elementIndex) {
27 | if ((elementIndex <= 0) && (elementIndex > maxHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
28 | return maxHeap.get(elementIndex - 1);
29 | }
30 |
31 | // Get the key of the element at a given index
32 | private double getElementKey(int elementIndex) {
33 | return maxHeap.get(elementIndex - 1).getKey();
34 | }
35 |
36 | // Swaps two elements in the heap
37 | private void swap(int index1, int index2) {
38 | HeapElement temporaryElement = maxHeap.get(index1 - 1);
39 | maxHeap.set(index1 - 1, maxHeap.get(index2 - 1));
40 | maxHeap.set(index2 - 1, temporaryElement);
41 | }
42 |
43 | // Toggle an element up to its right place as long as its key is lower than its parent's
44 | private void toggleUp(int elementIndex) {
45 | double key = maxHeap.get(elementIndex - 1).getKey();
46 | while (getElementKey((int) Math.floor(elementIndex/2)) < key) {
47 | swap(elementIndex, (int) Math.floor(elementIndex/2));
48 | elementIndex = (int) Math.floor(elementIndex/2);
49 | }
50 | }
51 |
52 | // Toggle an element down to its right place as long as its key is higher
53 | // than any of its children's
54 | private void toggleDown(int elementIndex) {
55 | double key = maxHeap.get(elementIndex - 1).getKey();
56 | boolean wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
57 | while ((2*elementIndex <= maxHeap.size()) && wrongOrder) {
58 | // Check whether it shall swap the element with its left child or its right one if any.
59 | if ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex*2 + 1) > getElementKey(elementIndex*2))) {
60 | swap(elementIndex, 2*elementIndex + 1);
61 | elementIndex = 2*elementIndex + 1;
62 | }
63 | else {
64 | swap(elementIndex, 2*elementIndex);
65 | elementIndex = 2*elementIndex;
66 | }
67 | wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
68 |
69 | }
70 | }
71 |
72 | private HeapElement extractMax() {
73 | HeapElement result = maxHeap.get(0);
74 | deleteElement(0);
75 | return result;
76 | }
77 |
78 | @Override
79 | public void insertElement(HeapElement element) {
80 | maxHeap.add(element);
81 | toggleUp(maxHeap.size());
82 |
83 | }
84 |
85 | @Override
86 | public void deleteElement(int elementIndex) {
87 | if (maxHeap.isEmpty())
88 | try {
89 | throw new EmptyHeapException("Attempt to delete an element from an empty heap");
90 | } catch (EmptyHeapException e) {
91 | e.printStackTrace();
92 | }
93 | if ((elementIndex > maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
94 | // The last element in heap replaces the one to be deleted
95 | maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
96 | maxHeap.remove(maxHeap.size());
97 | // Shall the new element be moved up...
98 | if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
99 | // ... or down ?
100 | else if (((2*elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2))) ||
101 | ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2)))) toggleDown(elementIndex);
102 | }
103 |
104 | @Override
105 | public HeapElement getElement() throws EmptyHeapException {
106 | try {
107 | return extractMax();
108 | } catch (Exception e) {
109 | throw new EmptyHeapException("Heap is empty. Error retrieving element");
110 | }
111 | }
112 |
113 | }
114 |
115 |
116 |
--------------------------------------------------------------------------------
/Data Structures/Heaps/MinHeap.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package heaps;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | /**
10 | * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
11 | * to its children's.
12 | * @author Nicolas Renard
13 | *
14 | */
15 | public class MinHeap implements Heap {
16 |
17 | private final List minHeap;
18 |
19 | public MinHeap(List listElements) throws Exception {
20 | minHeap = new ArrayList();
21 | for (HeapElement heapElement : listElements) {
22 | if (heapElement != null) insertElement(heapElement);
23 | else System.out.println("Null element. Not added to heap");
24 | }
25 | if (minHeap.size() == 0) System.out.println("No element has been added, empty heap.");
26 | }
27 |
28 | // Get the element at a given index. The key for the list is equal to index value - 1
29 | public HeapElement getElement(int elementIndex) {
30 | if ((elementIndex <= 0) && (elementIndex > minHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
31 | return minHeap.get(elementIndex - 1);
32 | }
33 |
34 | // Get the key of the element at a given index
35 | private double getElementKey(int elementIndex) {
36 | return minHeap.get(elementIndex - 1).getKey();
37 | }
38 |
39 | // Swaps two elements in the heap
40 | private void swap(int index1, int index2) {
41 | HeapElement temporaryElement = minHeap.get(index1 - 1);
42 | minHeap.set(index1 - 1, minHeap.get(index2 - 1));
43 | minHeap.set(index2 - 1, temporaryElement);
44 | }
45 |
46 | // Toggle an element up to its right place as long as its key is lower than its parent's
47 | private void toggleUp(int elementIndex) {
48 | double key = minHeap.get(elementIndex - 1).getKey();
49 | while (getElementKey((int) Math.floor(elementIndex/2)) > key) {
50 | swap(elementIndex, (int) Math.floor(elementIndex/2));
51 | elementIndex = (int) Math.floor(elementIndex/2);
52 | }
53 | }
54 |
55 | // Toggle an element down to its right place as long as its key is higher
56 | // than any of its children's
57 | private void toggleDown(int elementIndex) {
58 | double key = minHeap.get(elementIndex - 1).getKey();
59 | boolean wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
60 | while ((2*elementIndex <= minHeap.size()) && wrongOrder) {
61 | // Check whether it shall swap the element with its left child or its right one if any.
62 | if ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex*2 + 1) < getElementKey(elementIndex*2))) {
63 | swap(elementIndex, 2*elementIndex + 1);
64 | elementIndex = 2*elementIndex + 1;
65 | }
66 | else {
67 | swap(elementIndex, 2*elementIndex);
68 | elementIndex = 2*elementIndex;
69 | }
70 | wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
71 |
72 | }
73 | }
74 |
75 | private HeapElement extractMin() {
76 | HeapElement result = minHeap.get(0);
77 | deleteElement(0);
78 | return result;
79 | }
80 |
81 | @Override
82 | public void insertElement(HeapElement element) {
83 | minHeap.add(element);
84 | toggleUp(minHeap.size());
85 |
86 | }
87 |
88 | @Override
89 | public void deleteElement(int elementIndex) {
90 | if (minHeap.isEmpty())
91 | try {
92 | throw new EmptyHeapException("Attempt to delete an element from an empty heap");
93 | } catch (EmptyHeapException e) {
94 | e.printStackTrace();
95 | }
96 | if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
97 | // The last element in heap replaces the one to be deleted
98 | minHeap.set(elementIndex - 1, getElement(minHeap.size()));
99 | minHeap.remove(minHeap.size());
100 | // Shall the new element be moved up...
101 | if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
102 | // ... or down ?
103 | else if (((2*elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2))) ||
104 | ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2)))) toggleDown(elementIndex);
105 | }
106 |
107 | @Override
108 | public HeapElement getElement() throws EmptyHeapException {
109 | try {
110 | return extractMin();
111 | } catch (Exception e) {
112 | throw new EmptyHeapException("Heap is empty. Error retrieving element");
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/Others/LowestBasePalindrome.java:
--------------------------------------------------------------------------------
1 | import java.util.InputMismatchException;
2 | import java.util.Scanner;
3 |
4 | /**
5 | * Class for finding the lowest base in which a given integer is a palindrome.
6 | * Includes auxiliary methods for converting between bases and reversing strings.
7 | *
8 | * NOTE: There is potential for error, see note at line 63.
9 | *
10 | * @author RollandMichael
11 | * @version 2017.09.28
12 | *
13 | */
14 | public class LowestBasePalindrome {
15 |
16 | public static void main(String[] args) {
17 | Scanner in = new Scanner(System.in);
18 | int n=0;
19 | while (true) {
20 | try {
21 | System.out.print("Enter number: ");
22 | n = in.nextInt();
23 | break;
24 | } catch (InputMismatchException e) {
25 | System.out.println("Invalid input!");
26 | in.next();
27 | }
28 | }
29 | System.out.println(n+" is a palindrome in base "+lowestBasePalindrome(n));
30 | System.out.println(base2base(Integer.toString(n),10, lowestBasePalindrome(n)));
31 | }
32 |
33 | /**
34 | * Given a number in base 10, returns the lowest base in which the
35 | * number is represented by a palindrome (read the same left-to-right
36 | * and right-to-left).
37 | * @param num A number in base 10.
38 | * @return The lowest base in which num is a palindrome.
39 | */
40 | public static int lowestBasePalindrome(int num) {
41 | int base, num2=num;
42 | int digit;
43 | char digitC;
44 | boolean foundBase=false;
45 | String newNum = "";
46 | String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
47 |
48 | while (!foundBase) {
49 | // Try from bases 2 to num-1
50 | for (base=2; base0) {
53 | // Obtain the first digit of n in the current base,
54 | // which is equivalent to the integer remainder of (n/base).
55 | // The next digit is obtained by dividing n by the base and
56 | // continuing the process of getting the remainder. This is done
57 | // until n is <=0 and the number in the new base is obtained.
58 | digit = (num % base);
59 | num/=base;
60 | // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
61 | // form is just its value in ASCII.
62 |
63 | // NOTE: This may cause problems, as the capital letters are ASCII values
64 | // 65-90. It may cause false positives when one digit is, for instance 10 and assigned
65 | // 'A' from the character array and the other is 65 and also assigned 'A'.
66 |
67 | // Regardless, the character is added to the representation of n
68 | // in the current base.
69 | if (digit>=digits.length()) {
70 | digitC=(char)(digit);
71 | newNum+=digitC;
72 | continue;
73 | }
74 | newNum+=digits.charAt(digit);
75 | }
76 | // Num is assigned back its original value for the next iteration.
77 | num=num2;
78 | // Auxiliary method reverses the number.
79 | String reverse = reverse(newNum);
80 | // If the number is read the same as its reverse, then it is a palindrome.
81 | // The current base is returned.
82 | if (reverse.equals(newNum)) {
83 | foundBase=true;
84 | return base;
85 | }
86 | }
87 | }
88 | // If all else fails, n is always a palindrome in base n-1. ("11")
89 | return num-1;
90 | }
91 |
92 | private static String reverse(String str) {
93 | String reverse = "";
94 | for(int i=str.length()-1; i>=0; i--) {
95 | reverse += str.charAt(i);
96 | }
97 | return reverse;
98 | }
99 |
100 | private static String base2base(String n, int b1, int b2) {
101 | // Declare variables: decimal value of n,
102 | // character of base b1, character of base b2,
103 | // and the string that will be returned.
104 | int decimalValue = 0, charB2;
105 | char charB1;
106 | String output="";
107 | // Go through every character of n
108 | for (int i=0; i9 and store it in charB2
112 | if (charB1 >= 'A' && charB1 <= 'Z')
113 | charB2 = 10 + (charB1 - 'A');
114 | // Else, store the integer value in charB2
115 | else
116 | charB2 = charB1 - '0';
117 | // Convert the digit to decimal and add it to the
118 | // decimalValue of n
119 | decimalValue = decimalValue * b1 + charB2;
120 | }
121 |
122 | // Converting the decimal value to base b2:
123 | // A number is converted from decimal to another base
124 | // by continuously dividing by the base and recording
125 | // the remainder until the quotient is zero. The number in the
126 | // new base is the remainders, with the last remainder
127 | // being the left-most digit.
128 |
129 | // While the quotient is NOT zero:
130 | while (decimalValue != 0) {
131 | // If the remainder is a digit < 10, simply add it to
132 | // the left side of the new number.
133 | if (decimalValue % b2 < 10)
134 | output = Integer.toString(decimalValue % b2) + output;
135 | // If the remainder is >= 10, add a character with the
136 | // corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
137 | else
138 | output = (char)((decimalValue % b2)+55) + output;
139 | // Divide by the new base again
140 | decimalValue /= b2;
141 | }
142 | return output;
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/Sorts/HeapSort.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | * Heap Sort Algorithm
5 | * Implements MinHeap
6 | *
7 | * @author Unknown
8 | *
9 | */
10 | public class HeapSort {
11 | /** Array to store heap */
12 | private int[] heap;
13 | /** The size of the heap */
14 | private int size;
15 |
16 | /**
17 | * Constructor
18 | *
19 | * @param heap array of unordered integers
20 | */
21 | public HeapSort(int[] heap) {
22 | this.setHeap(heap);
23 | this.setSize(heap.length);
24 | }
25 |
26 | /**
27 | * Setter for variable size
28 | *
29 | * @param length new size
30 | */
31 | private void setSize(int length) {
32 | this.size = length;
33 | }
34 |
35 | /**
36 | * Setter for variable heap
37 | *
38 | * @param heap array of unordered elements
39 | */
40 | private void setHeap(int[] heap) {
41 | this.heap = heap;
42 | }
43 |
44 | /**
45 | * Swaps index of first with second
46 | *
47 | * @param first First index to switch
48 | * @param second Second index to switch
49 | */
50 | private void swap(int first, int second) {
51 | int temp = this.heap[first];
52 | this.heap[first] = this.heap[second];
53 | this.heap[second] = temp;
54 | }
55 |
56 | /**
57 | * Heapifies subtree from top as root to last as last child
58 | *
59 | * @param rootIndex index of root
60 | * @param lastChild index of last child
61 | */
62 | private void heapSubtree(int rootIndex, int lastChild) {
63 | int leftIndex = rootIndex * 2 + 1;
64 | int rightIndex = rootIndex * 2 + 2;
65 | int root = this.heap[rootIndex];
66 | if (rightIndex <= lastChild) { // if has right and left children
67 | int left = this.heap[leftIndex];
68 | int right = this.heap[rightIndex];
69 | if (left < right && left < root) {
70 | this.swap(leftIndex, rootIndex);
71 | this.heapSubtree(leftIndex, lastChild);
72 | } else if (right < root) {
73 | this.swap(rightIndex, rootIndex);
74 | this.heapSubtree(rightIndex, lastChild);
75 | }
76 | } else if (leftIndex <= lastChild) { // if no right child, but has left child
77 | int left = this.heap[leftIndex];
78 | if (left < root) {
79 | this.swap(leftIndex, rootIndex);
80 | this.heapSubtree(leftIndex, lastChild);
81 | }
82 | }
83 | }
84 |
85 | /**
86 | * Makes heap with root as root
87 | *
88 | * @param root index of root of heap
89 | */
90 | private void makeMinHeap(int root) {
91 | int leftIndex = root * 2 + 1;
92 | int rightIndex = root * 2 + 2;
93 | boolean hasLeftChild = leftIndex < this.heap.length;
94 | boolean hasRightChild = rightIndex < this.heap.length;
95 | if (hasRightChild) { //if has left and right
96 | this.makeMinHeap(leftIndex);
97 | this.makeMinHeap(rightIndex);
98 | this.heapSubtree(root, this.heap.length - 1);
99 | } else if (hasLeftChild) {
100 | this.heapSubtree(root, this.heap.length - 1);
101 | }
102 | }
103 |
104 | /**
105 | * Gets the root of heap
106 | *
107 | * @return root of heap
108 | */
109 | private int getRoot() {
110 | this.swap(0, this.size - 1);
111 | this.size--;
112 | this.heapSubtree(0, this.size - 1);
113 | return this.heap[this.size]; // return old root
114 | }
115 |
116 | /**
117 | * Sorts heap with heap sort; displays ordered elements to console.
118 | *
119 | * @return sorted array of sorted elements
120 | */
121 | public final int[] sort() {
122 | this.makeMinHeap(0); // make min heap using index 0 as root.
123 | int[] sorted = new int[this.size];
124 | int index = 0;
125 | while (this.size > 0) {
126 | int min = this.getRoot();
127 | sorted[index] = min;
128 | index++;
129 | }
130 | return sorted;
131 | }
132 |
133 | /**
134 | * Gets input to sort
135 | *
136 | * @return unsorted array of integers to sort
137 | */
138 | public static int[] getInput() {
139 | final int numElements = 6;
140 | int[] unsorted = new int[numElements];
141 | Scanner input = new Scanner(System.in);
142 | System.out.println("Enter any 6 Numbers for Unsorted Array : ");
143 | for (int i = 0; i < numElements; i++) {
144 | unsorted[i] = input.nextInt();
145 | }
146 | input.close();
147 | return unsorted;
148 | }
149 |
150 | /**
151 | * Prints elements in heap
152 | *
153 | * @param heap array representing heap
154 | */
155 | public static void printData(int[] heap) {
156 | System.out.println("Sorted Elements:");
157 | for (int i = 0; i < heap.length; i++) {
158 | System.out.print(" " + heap[i] + " ");
159 | }
160 | }
161 |
162 | /**
163 | * Main method
164 | *
165 | * @param args the command line arguments
166 | */
167 | public static void main(String[] args) {
168 | int[] heap = getInput();
169 | HeapSort data = new HeapSort(heap);
170 | int[] sorted = data.sort();
171 | printData(sorted);
172 | }
173 |
174 | }
175 |
--------------------------------------------------------------------------------