Browse Source

Codigo en Java de Arboles y Grafos

george 6 months ago
parent
commit
fab94cf9d6

BIN
.DS_Store


BIN
unidad3/.DS_Store


BIN
unidad3/java/.DS_Store


BIN
unidad4/c++/arbol_binario/cmake-build-debug/.ninja_deps


+ 2 - 0
unidad4/c++/arbol_binario/cmake-build-debug/.ninja_log

@@ -3,3 +3,5 @@
 347	375	1747590736968704279	arbol_binario	ad953bcdf104ff0e
 4	423	1747591768648454843	CMakeFiles/arbol_binario.dir/main.cpp.o	8338a5065830a245
 423	520	1747591769067551491	arbol_binario	ad953bcdf104ff0e
+15	496	1747670056645267920	CMakeFiles/arbol_binario.dir/main.cpp.o	8338a5065830a245
+496	626	1747670057125465143	arbol_binario	ad953bcdf104ff0e

BIN
unidad4/c++/arbol_binario/cmake-build-debug/arbol_binario


+ 374 - 0
unidad4/java/AVL_Tree/AVLTree.java

@@ -0,0 +1,374 @@
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * An AVL tree is a self-balancing binary search tree, and it was the first such
+ * data structure to be invented. In an AVL tree, the heights of the two child
+ * subtrees of any node differ by at most one. AVL trees are often compared with
+ * red-black trees because they support the same set of operations and because
+ * red-black trees also take O(log n) time for the basic operations. Because AVL
+ * trees are more rigidly balanced, they are faster than red-black trees for
+ * lookup intensive applications. However, red-black trees are faster for
+ * insertion and removal.
+ * <p>
+ * @see <a href="https://en.wikipedia.org/wiki/AVL_tree">AVL Tree (Wikipedia)</a>
+ * <br>
+ * @author Justin Wetherell <phishman3579@gmail.com>
+ */
+public class AVLTree<T extends Comparable<T>> extends BinarySearchTree<T> {
+
+    private enum Balance {
+        LEFT_LEFT, LEFT_RIGHT, RIGHT_LEFT, RIGHT_RIGHT
+    }
+
+    /**
+     * Default constructor.
+     */
+    public AVLTree() {
+        this.creator = new BinarySearchTree.INodeCreator<T>() {
+            /**
+             * {@inheritDoc}
+             */
+            @Override
+            public BinarySearchTree.Node<T> createNewNode(BinarySearchTree.Node<T> parent, T id) {
+                return (new AVLNode<T>(parent, id));
+            }
+        };
+    }
+
+    /**
+     * Constructor with external Node creator.
+     */
+    public AVLTree(INodeCreator<T> creator) {
+        super(creator);
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected Node<T> addValue(T id) {
+        Node<T> nodeToReturn = super.addValue(id);
+        AVLNode<T> nodeAdded = (AVLNode<T>) nodeToReturn;
+        nodeAdded.updateHeight();
+        balanceAfterInsert(nodeAdded);
+
+        nodeAdded = (AVLNode<T>) nodeAdded.parent;
+        while (nodeAdded != null) {
+            int h1 = nodeAdded.height;
+
+            nodeAdded.updateHeight();
+            balanceAfterInsert(nodeAdded);
+
+            // If height before and after balance is the same, stop going up the tree
+            int h2 = nodeAdded.height;
+            if (h1==h2)
+                break;
+
+            nodeAdded = (AVLNode<T>) nodeAdded.parent;
+        }
+        return nodeToReturn;
+    }
+
+    /**
+     * Balance the tree according to the AVL post-insert algorithm.
+     * 
+     * @param node
+     *            Root of tree to balance.
+     */
+    private void balanceAfterInsert(AVLNode<T> node) {
+        int balanceFactor = node.getBalanceFactor();
+        if (balanceFactor > 1 || balanceFactor < -1) {
+            AVLNode<T> child = null;
+            Balance balance = null;
+            if (balanceFactor < 0) {
+                child = (AVLNode<T>) node.lesser;
+                balanceFactor = child.getBalanceFactor();
+                if (balanceFactor < 0)
+                    balance = Balance.LEFT_LEFT;
+                else 
+                    balance = Balance.LEFT_RIGHT;
+            } else {
+                child = (AVLNode<T>) node.greater;
+                balanceFactor = child.getBalanceFactor();
+                if (balanceFactor < 0)
+                    balance = Balance.RIGHT_LEFT;
+                else
+                    balance = Balance.RIGHT_RIGHT;
+            }
+
+            if (balance == Balance.LEFT_RIGHT) {
+                // Left-Right (Left rotation, right rotation)
+                rotateLeft(child);
+                rotateRight(node);
+            } else if (balance == Balance.RIGHT_LEFT) {
+                // Right-Left (Right rotation, left rotation)
+                rotateRight(child);
+                rotateLeft(node);
+            } else if (balance == Balance.LEFT_LEFT) {
+                // Left-Left (Right rotation)
+                rotateRight(node);
+            } else {
+                // Right-Right (Left rotation)
+                rotateLeft(node);
+            }
+
+            child.updateHeight();
+            node.updateHeight();
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected Node<T> removeValue(T value) {
+        // Find node to remove
+        Node<T> nodeToRemoved = this.getNode(value);
+        if (nodeToRemoved==null)
+            return null;
+
+        // Find the replacement node
+        Node<T> replacementNode = this.getReplacementNode(nodeToRemoved);
+
+        // Find the parent of the replacement node to re-factor the height/balance of the tree
+        AVLNode<T> nodeToRefactor = null;
+        if (replacementNode != null)
+            nodeToRefactor = (AVLNode<T>) replacementNode.parent;
+        if (nodeToRefactor == null)
+            nodeToRefactor = (AVLNode<T>) nodeToRemoved.parent;
+        if (nodeToRefactor != null && nodeToRefactor == nodeToRemoved)
+            nodeToRefactor = (AVLNode<T>) replacementNode;
+
+        // Replace the node
+        replaceNodeWithNode(nodeToRemoved, replacementNode);
+
+        // Re-balance the tree all the way up the tree
+        while (nodeToRefactor != null) {
+            nodeToRefactor.updateHeight();
+            balanceAfterDelete(nodeToRefactor);
+
+            nodeToRefactor = (AVLNode<T>) nodeToRefactor.parent;
+        }
+
+        return nodeToRemoved;
+    }
+
+    /**
+     * Balance the tree according to the AVL post-delete algorithm.
+     * 
+     * @param node
+     *            Root of tree to balance.
+     */
+    private void balanceAfterDelete(AVLNode<T> node) {
+        int balanceFactor = node.getBalanceFactor();
+        if (balanceFactor == -2 || balanceFactor == 2) {
+            if (balanceFactor == -2) {
+                AVLNode<T> ll = (AVLNode<T>) node.lesser.lesser;
+                int lesser = (ll != null) ? ll.height : 0;
+                AVLNode<T> lr = (AVLNode<T>) node.lesser.greater;
+                int greater = (lr != null) ? lr.height : 0;
+                if (lesser >= greater) {
+                    rotateRight(node);
+                    node.updateHeight();
+                    if (node.parent != null)
+                        ((AVLNode<T>) node.parent).updateHeight();
+                } else {
+                    rotateLeft(node.lesser);
+                    rotateRight(node);
+
+                    AVLNode<T> p = (AVLNode<T>) node.parent;
+                    if (p.lesser != null)
+                        ((AVLNode<T>) p.lesser).updateHeight();
+                    if (p.greater != null)
+                        ((AVLNode<T>) p.greater).updateHeight();
+                    p.updateHeight();
+                }
+            } else if (balanceFactor == 2) {
+                AVLNode<T> rr = (AVLNode<T>) node.greater.greater;
+                int greater = (rr != null) ? rr.height : 0;
+                AVLNode<T> rl = (AVLNode<T>) node.greater.lesser;
+                int lesser = (rl != null) ? rl.height : 0;
+                if (greater >= lesser) {
+                    rotateLeft(node);
+                    node.updateHeight();
+                    if (node.parent != null)
+                        ((AVLNode<T>) node.parent).updateHeight();
+                } else {
+                    rotateRight(node.greater);
+                    rotateLeft(node);
+
+                    AVLNode<T> p = (AVLNode<T>) node.parent;
+                    if (p.lesser != null)
+                        ((AVLNode<T>) p.lesser).updateHeight();
+                    if (p.greater != null)
+                        ((AVLNode<T>) p.greater).updateHeight();
+                    p.updateHeight();
+                }
+            }
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected boolean validateNode(Node<T> node) {
+        boolean bst = super.validateNode(node);
+        if (!bst)
+            return false;
+
+        AVLNode<T> avlNode = (AVLNode<T>) node;
+        int balanceFactor = avlNode.getBalanceFactor();
+        if (balanceFactor > 1 || balanceFactor < -1) {
+            return false;
+        }
+        if (avlNode.isLeaf()) {
+            if (avlNode.height != 1)
+                return false;
+        } else {
+            AVLNode<T> avlNodeLesser = (AVLNode<T>) avlNode.lesser;
+            int lesserHeight = 1;
+            if (avlNodeLesser != null)
+                lesserHeight = avlNodeLesser.height;
+
+            AVLNode<T> avlNodeGreater = (AVLNode<T>) avlNode.greater;
+            int greaterHeight = 1;
+            if (avlNodeGreater != null)
+                greaterHeight = avlNodeGreater.height;
+
+            if (avlNode.height == (lesserHeight + 1) || avlNode.height == (greaterHeight + 1))
+                return true;
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public String toString() {
+        return AVLTreePrinter.getString(this);
+    }
+
+    protected static class AVLNode<T extends Comparable<T>> extends Node<T> {
+
+        protected int height = 1;
+
+        /**
+         * Constructor for an AVL node
+         * 
+         * @param parent
+         *            Parent of the node in the tree, can be NULL.
+         * @param value
+         *            Value of the node in the tree.
+         */
+        protected AVLNode(Node<T> parent, T value) {
+            super(parent, value);
+        }
+
+        /**
+         * Determines is this node is a leaf (has no children).
+         * 
+         * @return True if this node is a leaf.
+         */
+        protected boolean isLeaf() {
+            return ((lesser == null) && (greater == null));
+        }
+
+        /**
+         * Updates the height of this node based on it's children.
+         */
+        protected int updateHeight() {
+            int lesserHeight = 0;
+            if (lesser != null) {
+                AVLNode<T> lesserAVLNode = (AVLNode<T>) lesser;
+                lesserHeight = lesserAVLNode.height;
+            }
+            int greaterHeight = 0;
+            if (greater != null) {
+                AVLNode<T> greaterAVLNode = (AVLNode<T>) greater;
+                greaterHeight = greaterAVLNode.height;
+            }
+
+            if (lesserHeight > greaterHeight) {
+                height = lesserHeight + 1;
+            } else {
+                height = greaterHeight + 1;
+            }
+            return height;
+        }
+
+        /**
+         * Get the balance factor for this node.
+         * 
+         * @return An integer representing the balance factor for this node. It
+         *         will be negative if the lesser branch is longer than the
+         *         greater branch.
+         */
+        protected int getBalanceFactor() {
+            int lesserHeight = 0;
+            if (lesser != null) {
+                AVLNode<T> lesserAVLNode = (AVLNode<T>) lesser;
+                lesserHeight = lesserAVLNode.height;
+            }
+            int greaterHeight = 0;
+            if (greater != null) {
+                AVLNode<T> greaterAVLNode = (AVLNode<T>) greater;
+                greaterHeight = greaterAVLNode.height;
+            }
+            return greaterHeight - lesserHeight;
+        }
+
+        /**
+         * {@inheritDoc}
+         */
+        @Override
+        public String toString() {
+            return "value=" + id + " height=" + height + " parent=" + ((parent != null) ? parent.id : "NULL")
+                    + " lesser=" + ((lesser != null) ? lesser.id : "NULL") + " greater="
+                    + ((greater != null) ? greater.id : "NULL");
+        }
+    }
+
+    protected static class AVLTreePrinter {
+
+        public static <T extends Comparable<T>> String getString(AVLTree<T> tree) {
+            if (tree.root == null)
+                return "Tree has no nodes.";
+            return getString((AVLNode<T>) tree.root, "", true);
+        }
+
+        public static <T extends Comparable<T>> String getString(AVLNode<T> node) {
+            if (node == null)
+                return "Sub-tree has no nodes.";
+            return getString(node, "", true);
+        }
+
+        private static <T extends Comparable<T>> String getString(AVLNode<T> node, String prefix, boolean isTail) {
+            StringBuilder builder = new StringBuilder();
+
+            builder.append(prefix + (isTail ? "└── " : "├── ") + "(" + node.height + ") " + node.id + "\n");
+            List<Node<T>> children = null;
+            if (node.lesser != null || node.greater != null) {
+                children = new ArrayList<Node<T>>(2);
+                if (node.lesser != null)
+                    children.add(node.lesser);
+                if (node.greater != null)
+                    children.add(node.greater);
+            }
+            if (children != null) {
+                for (int i = 0; i < children.size() - 1; i++) {
+                    builder.append(getString((AVLNode<T>) children.get(i), prefix + (isTail ? "    " : "│   "), false));
+                }
+                if (children.size() >= 1) {
+                    builder.append(getString((AVLNode<T>) children.get(children.size() - 1), prefix + (isTail ? "    " : "│   "), true));
+                }
+            }
+
+            return builder.toString();
+        }
+    }
+}

+ 177 - 0
unidad4/java/BTree/BTree.java

@@ -0,0 +1,177 @@
+// Java Program for Implementaion B-Tree
+
+class BTreeNode {
+    // Variables Declared    
+    int[] keys; // Array to store keys 
+    int t; // Minimum degree (defines the range for number of keys)
+    BTreeNode[] children; // Array to store child pointers
+    int n; // Current number of keys
+    boolean leaf; // True when node is leaf, else False
+
+    public BTreeNode(int t, boolean leaf) {
+        this.t = t;
+        this.leaf = leaf;
+
+        keys = new int[2 * t - 1];
+        children = new BTreeNode[2 * t];
+        n = 0;
+    }
+
+    // Function to search given key in subtree
+    // rooted with this node
+    public BTreeNode search(int key) {
+        int i = 0;
+
+        while (i < n && key > keys[i])
+            i++;
+
+        if (keys[i] == key)
+            return this;
+
+        if (leaf)
+            return null;
+
+        return children[i].search(key);
+    }
+
+    // Function to insert a new key
+    // in subtree rooted with this node
+    public void insertNonFull(int key) {
+        int i = n - 1;
+
+        if (leaf) {
+            while (i >= 0 && key < keys[i]) {
+                keys[i + 1] = keys[i];
+                i--;
+            }
+            keys[i + 1] = key;
+            n++;
+        } else {
+            while (i >= 0 && key < keys[i])
+                i--;
+            i++;
+
+            if (children[i].n == 2 * t - 1) {
+                splitChild(i, children[i]);
+                if (key > keys[i])
+                    i++;
+            }
+            children[i].insertNonFull(key);
+        }
+    }
+
+    // Function to split the child node
+    public void splitChild(int i, BTreeNode y) {
+        BTreeNode z = new BTreeNode(y.t, y.leaf);
+        z.n = t - 1;
+
+        for (int j = 0; j < t - 1; j++)
+            z.keys[j] = y.keys[j + t];
+
+        if (!y.leaf) {
+            for (int j = 0; j < t; j++)
+                z.children[j] = y.children[j + t];
+        }
+
+        y.n = t - 1;
+
+        for (int j = n; j >= i + 1; j--)
+            children[j + 1] = children[j];
+
+        children[i + 1] = z;
+
+        for (int j = n - 1; j >= i; j--)
+            keys[j + 1] = keys[j];
+
+        keys[i] = y.keys[t - 1];
+        n++;
+    }
+
+    // Function to print all keys in the
+      // subtree rooted with this node
+    public void printInOrder() {
+        int i;
+
+        for (i = 0; i < n; i++) {
+            if (!leaf)
+                children[i].printInOrder();
+            System.out.print(keys[i] + " ");
+        }
+
+        if (!leaf)
+            children[i].printInOrder();
+    }
+}
+
+public class BTree {
+    // Pointer to root node
+    private BTreeNode root;
+
+    // Minimum degree
+    private int t;
+
+    public BTree(int t) {
+        this.t = t;
+        root = null;
+    }
+
+    // Function to search a key in this tree
+    public BTreeNode search(int key) {
+        return (root == null) ? null : root.search(key);
+    }
+
+    // Function to insert a key into the B-tree
+    public void insert(int key) {
+        if (root == null) {
+            root = new BTreeNode(t, true);
+            root.keys[0] = key;
+            root.n = 1;
+        } else {
+            if (root.n == 2 * t - 1) {
+                BTreeNode newRoot = new BTreeNode(t, false);
+                newRoot.children[0] = root;
+                newRoot.splitChild(0, root);
+
+                int i = 0;
+
+                if (newRoot.keys[0] < key)
+                    i++;
+
+                newRoot.children[i].insertNonFull(key);
+                root = newRoot;
+            } else {
+                root.insertNonFull(key);
+            }
+        }
+    }
+
+    // Function to print the entire B-tree
+    public void printBTree() {
+        if (root != null)
+            root.printInOrder();
+
+        System.out.println();
+    }
+
+    public static void main(String[] args) {
+        // Create a B-tree with minimum degree 3
+        BTree bTree = new BTree(3);
+        bTree.insert(10);
+        bTree.insert(20);
+        bTree.insert(5);
+        bTree.insert(6);
+        bTree.insert(12);
+        bTree.insert(30);
+
+        System.out.print("B-tree : ");
+        bTree.printBTree();
+
+        int searchKey = 6;
+        BTreeNode foundNode = bTree.search(searchKey);
+
+        if (foundNode != null)
+            System.out.println("Key " + searchKey + " found in the B-tree.");
+        else
+            System.out.println("Key " + searchKey + " not found in the B-tree.");
+    }
+}

+ 65 - 0
unidad4/java/BTree/BTree2.java

@@ -0,0 +1,65 @@
+// Node class representing each node in the BST
+class TreeNode {
+    int value;
+    TreeNode left, right;
+
+    TreeNode(int item) {
+        value = item;
+        left = right = null;
+    }
+}
+
+// BinarySearchTree class with basic operations
+class BinarySearchTree {
+    TreeNode root;
+
+    // Method to insert a new value
+    void insert(int value) {
+        root = insertRec(root, value);
+    }
+
+    // Recursive method to insert a new value
+    TreeNode insertRec(TreeNode node, int value) {
+        if (node == null) {
+            node = new TreeNode(value);
+            return node;
+        }
+        if (value < node.value) {
+            node.left = insertRec(node.left, value);
+        } else if (value > node.value) {
+            node.right = insertRec(node.right, value);
+        }
+        return node;
+    }
+
+    // Method to perform an in-order traversal
+    void inorder() {
+        inorderRec(root);
+    }
+
+    // Recursive method to perform in-order traversal
+    void inorderRec(TreeNode node) {
+        if (node != null) {
+            inorderRec(node.left);
+            System.out.print(node.value + " ");
+            inorderRec(node.right);
+        }
+    }
+}
+
+// Main class to test the BinarySearchTree implementation
+public class BTree2 {
+    public static void main(String[] args) {
+        BinarySearchTree bst = new BinarySearchTree();
+        bst.insert(30);
+        bst.insert(50);
+        bst.insert(20);
+        bst.insert(40);
+        bst.insert(70);
+        bst.insert(60);
+        bst.insert(80);
+
+        System.out.println("In-order traversal of the BST:");
+        bst.inorder();
+    }
+}

+ 65 - 0
unidad4/java/Grafo_dirigido/GFG_direct.java

@@ -0,0 +1,65 @@
+// Java Program to Implement the Directed Graph
+// Using Linked List
+
+// Importing standard classes from respectively packages
+import java.io.*;
+import java.util.*;
+
+// Main class
+class GFG_direct {
+
+    // Method 1
+    // To make pair of nodes
+    static void
+    addEdge(LinkedList<LinkedList<Integer> > Adj, int u,
+            int v)
+    {
+        // Creating unidirectional vertex
+        Adj.get(u).add(v);
+    }
+
+    // Method 2
+    // To print the adjacency List
+    static void
+    printadjacencylist(LinkedList<LinkedList<Integer> > adj)
+    {
+        for (int i = 0; i < adj.size(); ++i) {
+
+            // Printing the head
+            if (adj.get(i).size() != 0) {
+                System.out.print(i + "->");
+                for (int v : adj.get(i)) {
+
+                    // Printing the nodes
+                    System.out.print(v + " ");
+                }
+
+                // A new line is needed
+                System.out.println();
+            }
+        }
+    }
+
+    // Method 3
+    // Main driver method
+    public static void main(String[] args)
+    {
+        // Creating vertex
+        int V = 5;
+
+        LinkedList<LinkedList<Integer> > adj
+            = new LinkedList<LinkedList<Integer> >();
+
+        for (int i = 0; i < V; ++i) {
+            adj.add(new LinkedList<Integer>());
+        }
+        // Inserting nodes
+        // Custom input elements
+        addEdge(adj, 0, 1);
+        addEdge(adj, 0, 4);
+        addEdge(adj, 1, 2);
+
+        // Printing adjacency List
+        printadjacencylist(adj);
+    }
+}

+ 69 - 0
unidad4/java/Grafos/GFG.java

@@ -0,0 +1,69 @@
+// Java Program to Implement the Unidirectional Graph
+// Using Linked List
+
+// Importing required classes from packages
+import java.io.*;
+import java.util.*;
+
+// Main class
+class GFG {
+
+    // Method 1
+    // To make pair of nodes
+    static void
+    addEdge(LinkedList<LinkedList<Integer> > Adj, int u,
+            int v)
+    {
+        // Creating bi-directional vertex
+        Adj.get(u).add(v);
+        Adj.get(v).add(u);
+    }
+
+    // Method 2
+    // To print the adjacency list
+    static void
+    printadjacencylist(LinkedList<LinkedList<Integer> > adj)
+    {
+        for (int i = 0; i < adj.size(); ++i) {
+
+            // Printing the head
+            System.out.print(i + "->");
+
+            for (int v : adj.get(i)) {
+                // Printing the nodes
+                System.out.print(v + " ");
+            }
+
+            // Now a new line is needed
+            System.out.println();
+        }
+    }
+
+    // Method 3
+    // Main driver method
+    public static void main(String[] args)
+    {
+
+        // Creating vertex
+        int V = 5;
+
+        LinkedList<LinkedList<Integer> > adj
+            = new LinkedList<LinkedList<Integer> >();
+        for (int i = 0; i < V; ++i) {
+            adj.add(new LinkedList<Integer>());
+        }
+
+        // Inserting nodes
+        // Custom input node elements
+        addEdge(adj, 0, 1);
+        addEdge(adj, 0, 4);
+        addEdge(adj, 1, 2);
+        addEdge(adj, 1, 3);
+        addEdge(adj, 1, 4);
+        addEdge(adj, 2, 3);
+        addEdge(adj, 3, 4);
+
+        // Printing adjacency list
+        printadjacencylist(adj);
+    }
+}

+ 151 - 0
unidad4/java/Grafos/Graph_generic.java

@@ -0,0 +1,151 @@
+// Java program to implement Graph
+// with the help of Generics
+
+import java.util.*;
+
+class Graph<T> {
+
+    // We use Hashmap to store the edges in the graph
+    private Map<T, List<T> > map = new HashMap<>();
+
+    // This function adds a new vertex to the graph
+    public void addVertex(T s)
+    {
+        map.put(s, new LinkedList<T>());
+    }
+
+    // This function adds the edge
+    // between source to destination
+    public void addEdge(T source, T destination,
+                        boolean bidirectional)
+    {
+
+        if (!map.containsKey(source))
+            addVertex(source);
+
+        if (!map.containsKey(destination))
+            addVertex(destination);
+
+        map.get(source).add(destination);
+        if (bidirectional == true) {
+            map.get(destination).add(source);
+        }
+    }
+
+    // This function gives the count of vertices
+    public void getVertexCount()
+    {
+        System.out.println("The graph has "
+                           + map.keySet().size()
+                           + " vertex");
+    }
+
+    // This function gives the count of edges
+    public void getEdgesCount(boolean bidirection)
+    {
+        int count = 0;
+        for (T v : map.keySet()) {
+            count += map.get(v).size();
+        }
+        if (bidirection == true) {
+            count = count / 2;
+        }
+        System.out.println("The graph has " + count
+                           + " edges.");
+    }
+
+    // This function gives whether
+    // a vertex is present or not.
+    public void hasVertex(T s)
+    {
+        if (map.containsKey(s)) {
+            System.out.println("The graph contains " + s
+                               + " as a vertex.");
+        }
+        else {
+            System.out.println("The graph does not contain "
+                               + s + " as a vertex.");
+        }
+    }
+
+    // This function gives whether an edge is present or
+    // not.
+    public void hasEdge(T s, T d)
+    {
+        if (map.get(s).contains(d)) {
+            System.out.println(
+                "The graph has an edge between " + s
+                + " and " + d + ".");
+        }
+        else {
+            System.out.println(
+                "The graph has no edge between " + s
+                + " and " + d + ".");
+        }
+    }
+  
+      public void neighbours(T s)
+    {
+        if(!map.containsKey(s)) 
+        return ;
+        System.out.println("The neighbours of "+s+" are");
+        for(T w:map.get(s))
+         System.out.print(w+",");
+    }
+
+    // Prints the adjancency list of each vertex.
+    @Override public String toString()
+    {
+        StringBuilder builder = new StringBuilder();
+
+        for (T v : map.keySet()) {
+            builder.append(v.toString() + ": ");
+            for (T w : map.get(v)) {
+                builder.append(w.toString() + " ");
+            }
+            builder.append("\n");
+        }
+
+        return (builder.toString());
+    }
+}
+
+// Driver Code
+public class Graph_generic {
+
+    public static void main(String args[])
+    {
+
+        // Object of graph is created.
+        
+        Graph<Integer> g = new Graph<Integer>();
+
+        // edges are added.
+        // Since the graph is bidirectional,
+        // so boolean bidirectional is passed as true.
+        g.addEdge(0, 1, true);
+        g.addEdge(0, 4, true);
+        g.addEdge(1, 2, true);
+        g.addEdge(1, 3, true);
+        g.addEdge(1, 4, true);
+        g.addEdge(2, 3, true);
+        g.addEdge(3, 4, true);
+
+        // Printing the graph
+        System.out.println("Graph:\n" + g.toString());
+
+        // Gives the no of vertices in the graph.
+        g.getVertexCount();
+
+        // Gives the no of edges in the graph.
+        g.getEdgesCount(true);
+
+        // Tells whether the edge is present or not.
+        g.hasEdge(3, 4);
+
+        // Tells whether vertex is present or not
+        g.hasVertex(5);
+               g.neighbours(1);
+
+    }
+}

+ 46 - 0
unidad5/java/BinarySearch.java

@@ -0,0 +1,46 @@
+// Java implementation of recursive
+// Binary Search
+
+class BinarySearch {
+	// Function that returns index of
+	// x if it is present in arr[l, r]
+	int binarySearch(int arr[], int l,int r, int x) {
+		if (r >= l) {
+			int mid = l + (r - l) / 2;
+			// If the element is present
+			// at the middle itself
+			if (arr[mid] == x)
+				return mid;
+
+			// If element is smaller than
+			// mid, then it can only be
+			// present in left subarray
+			if (arr[mid] > x)
+				return binarySearch(arr, l, mid - 1, x);
+			// Else the element can only be
+			// present in right subarray
+			return binarySearch(arr, mid + 1, r, x);
+		}
+		// Reach here when element is
+		// not present in array
+		return -1;
+	}
+
+	// Driver Code
+	public static void main(String args[]) {
+		// Create object of this class
+		BinarySearch ob = new BinarySearch();
+		// Given array arr[]
+		int arr[] = { 2, 3, 4, 10, 40 };
+		int n = arr.length;
+		int x = 10;
+
+		// Function Call
+		int result = ob.binarySearch(arr, 0, n - 1, x);
+
+		if (result == -1)
+			System.out.println("Element " + "not present");
+		else
+			System.out.println("Element found" + " at index " + result);
+	}
+}

+ 47 - 0
unidad5/java/BubbleSort.java

@@ -0,0 +1,47 @@
+// Optimized java implementation of Bubble sort
+// https://www.geeksforgeeks.org/bubble-sort-algorithm/
+import java.io.*;
+
+class BubbleSort {
+    
+    // An optimized version of Bubble Sort
+    static void bubbleSort(int arr[], int n){
+        int i, j, temp;
+        boolean swapped;
+        for (i = 0; i < n - 1; i++) {
+            swapped = false;
+            for (j = 0; j < n - i - 1; j++) {
+                if (arr[j] > arr[j + 1]) {
+                    
+                    // Swap arr[j] and arr[j+1]
+                    temp = arr[j];
+                    arr[j] = arr[j + 1];
+                    arr[j + 1] = temp;
+                    swapped = true;
+                }
+            }
+
+            // If no two elements were
+            // swapped by inner loop, then break
+            if (swapped == false)
+                break;
+        }
+    }
+
+    // Function to print an array
+    static void printArray(int arr[], int size){
+        int i;
+        for (i = 0; i < size; i++)
+            System.out.print(arr[i] + " ");
+        System.out.println();
+    }
+
+    // Driver program
+    public static void main(String args[]){
+        int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
+        int n = arr.length;
+        bubbleSort(arr, n);
+        System.out.println("Sorted array: ");
+        printArray(arr, n);
+    }
+}

+ 35 - 0
unidad5/java/LinearSearch.java

@@ -0,0 +1,35 @@
+// Java program to implement Linear Search
+
+class LinearSearch {
+
+	// Function for linear search
+	public static int search(int arr[], int x) {
+		int n = arr.length;
+		// Traverse array arr[]
+		for (int i = 0; i < n; i++) {
+			// If element found then
+			// return that index
+			if (arr[i] == x)
+				return i;
+		}
+		return -1;
+	}
+
+	// Driver Code
+	public static void main(String args[])
+	{
+		// Given arr[]
+		int arr[] = { 2, 3, 4, 10, 40 };
+		// Element to search
+		int x = 10;
+		// Function Call
+		int result = search(arr, x);
+		if (result == -1)
+			System.out.print(
+				"Element is not present in array");
+		else
+			System.out.print("Element is present"
+							+ " at index "
+							+ result);
+	}
+}

+ 100 - 0
unidad5/java/MergeSort.java

@@ -0,0 +1,100 @@
+// Java program for Merge Sort
+// https://www.geeksforgeeks.org/merge-sort/
+import java.io.*;
+
+class MergeSort  {
+
+    // Merges two subarrays of arr[].
+    // First subarray is arr[l..m]
+    // Second subarray is arr[m+1..r]
+    static void merge(int arr[], int l, int m, int r)
+    {
+        // Find sizes of two subarrays to be merged
+        int n1 = m - l + 1;
+        int n2 = r - m;
+
+        // Create temp arrays
+        int L[] = new int[n1];
+        int R[] = new int[n2];
+
+        // Copy data to temp arrays
+        for (int i = 0; i < n1; ++i)
+            L[i] = arr[l + i];
+        for (int j = 0; j < n2; ++j)
+            R[j] = arr[m + 1 + j];
+
+        // Merge the temp arrays
+
+        // Initial indices of first and second subarrays
+        int i = 0, j = 0;
+
+        // Initial index of merged subarray array
+        int k = l;
+        while (i < n1 && j < n2) {
+            if (L[i] <= R[j]) {
+                arr[k] = L[i];
+                i++;
+            }
+            else {
+                arr[k] = R[j];
+                j++;
+            }
+            k++;
+        }
+
+        // Copy remaining elements of L[] if any
+        while (i < n1) {
+            arr[k] = L[i];
+            i++;
+            k++;
+        }
+
+        // Copy remaining elements of R[] if any
+        while (j < n2) {
+            arr[k] = R[j];
+            j++;
+            k++;
+        }
+    }
+
+    // Main function that sorts arr[l..r] using
+    // merge()
+    static void sort(int arr[], int l, int r)
+    {
+        if (l < r) {
+
+            // Find the middle point
+            int m = l + (r - l) / 2;
+
+            // Sort first and second halves
+            sort(arr, l, m);
+            sort(arr, m + 1, r);
+
+            // Merge the sorted halves
+            merge(arr, l, m, r);
+        }
+    }
+
+    // A utility function to print array of size n
+    static void printArray(int arr[])
+    {
+        int n = arr.length;
+        for (int i = 0; i < n; ++i)
+            System.out.print(arr[i] + " ");
+        System.out.println();
+    }
+
+    // Driver code
+    public static void main(String args[])
+    {
+        int arr[] = { 12, 11, 13, 5, 6, 7 };
+
+        System.out.println("Given array is");
+        printArray(arr);
+
+        sort(arr, 0, arr.length - 1);
+
+        System.out.println("\nSorted array is");
+        printArray(arr);
+    }
+}

+ 63 - 0
unidad5/java/QuickSort.java

@@ -0,0 +1,63 @@
+// https://www.geeksforgeeks.org/quick-sort-algorithm/
+import java.util.Arrays;
+
+class QuickSort {
+
+    // Partition function
+    static int partition(int[] arr, int low, int high) {
+        
+        // Choose the pivot
+        int pivot = arr[high];
+        
+        // Index of smaller element and indicates 
+        // the right position of pivot found so far
+        int i = low - 1;
+
+        // Traverse arr[low..high] and move all smaller
+        // elements to the left side. Elements from low to 
+        // i are smaller after every iteration
+        for (int j = low; j <= high - 1; j++) {
+            if (arr[j] < pivot) {
+                i++;
+                swap(arr, i, j);
+            }
+        }
+        
+        // Move pivot after smaller elements and
+        // return its position
+        swap(arr, i + 1, high);  
+        return i + 1;
+    }
+
+    // Swap function
+    static void swap(int[] arr, int i, int j) {
+        int temp = arr[i];
+        arr[i] = arr[j];
+        arr[j] = temp;
+    }
+
+    // The QuickSort function implementation
+    static void quickSort(int[] arr, int low, int high) {
+        if (low < high) {
+            
+            // pi is the partition return index of pivot
+            int pi = partition(arr, low, high);
+
+            // Recursion calls for smaller elements
+            // and greater or equals elements
+            quickSort(arr, low, pi - 1);
+            quickSort(arr, pi + 1, high);
+        }
+    }
+
+    public static void main(String[] args) {
+        int[] arr = {10, 7, 8, 9, 1, 5};
+        int n = arr.length;
+      
+        quickSort(arr, 0, n - 1);
+        
+        for (int val : arr) {
+            System.out.print(val + " ");  
+        }
+    }
+}

+ 80 - 0
unidad5/java/Radix.java

@@ -0,0 +1,80 @@
+// Radix sort Java implementation
+// https://geeksforgeeks.org/radix-sort/
+import java.io.*;
+import java.util.*;
+
+class Radix {
+
+    // A utility function to get maximum value in arr[]
+    static int getMax(int arr[], int n)
+    {
+        int mx = arr[0];
+        for (int i = 1; i < n; i++)
+            if (arr[i] > mx)
+                mx = arr[i];
+        return mx;
+    }
+
+    // A function to do counting sort of arr[] according to
+    // the digit represented by exp.
+    static void countSort(int arr[], int n, int exp)
+    {
+        int output[] = new int[n]; // output array
+        int i;
+        int count[] = new int[10];
+        Arrays.fill(count, 0);
+
+        // Store count of occurrences in count[]
+        for (i = 0; i < n; i++)
+            count[(arr[i] / exp) % 10]++;
+
+        // Change count[i] so that count[i] now contains
+        // actual position of this digit in output[]
+        for (i = 1; i < 10; i++)
+            count[i] += count[i - 1];
+
+        // Build the output array
+        for (i = n - 1; i >= 0; i--) {
+            output[count[(arr[i] / exp) % 10] - 1] = arr[i];
+            count[(arr[i] / exp) % 10]--;
+        }
+
+        // Copy the output array to arr[], so that arr[] now
+        // contains sorted numbers according to current
+        // digit
+        for (i = 0; i < n; i++)
+            arr[i] = output[i];
+    }
+
+    // The main function to that sorts arr[] of
+    // size n using Radix Sort
+    static void radixsort(int arr[], int n)
+    {
+        // Find the maximum number to know number of digits
+        int m = getMax(arr, n);
+
+        // Do counting sort for every digit. Note that
+        // instead of passing digit number, exp is passed.
+        // exp is 10^i where i is current digit number
+        for (int exp = 1; m / exp > 0; exp *= 10)
+            countSort(arr, n, exp);
+    }
+
+    // A utility function to print an array
+    static void print(int arr[], int n)
+    {
+        for (int i = 0; i < n; i++)
+            System.out.print(arr[i] + " ");
+    }
+
+    // Main driver method
+    public static void main(String[] args)
+    {
+        int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
+        int n = arr.length;
+
+        // Function Call
+        radixsort(arr, n);
+        print(arr, n);
+    }
+}

+ 61 - 0
unidad5/java/ShellSort.java

@@ -0,0 +1,61 @@
+// Java implementation of ShellSort
+// https://www.geeksforgeeks.org/shell-sort/
+class ShellSort
+{
+    /* An utility function to print array of size n*/
+    static void printArray(int arr[])
+    {
+        int n = arr.length;
+        for (int i=0; i<n; ++i)
+            System.out.print(arr[i] + " ");
+        System.out.println();
+    }
+
+    /* function to sort arr using shellSort */
+    int sort(int arr[])
+    {
+        int n = arr.length;
+
+        // Start with a big gap, then reduce the gap
+        for (int gap = n/2; gap > 0; gap /= 2)
+        {
+            // Do a gapped insertion sort for this gap size.
+            // The first gap elements a[0..gap-1] are already
+            // in gapped order keep adding one more element
+            // until the entire array is gap sorted
+            for (int i = gap; i < n; i += 1)
+            {
+                // add a[i] to the elements that have been gap
+                // sorted save a[i] in temp and make a hole at
+                // position i
+                int temp = arr[i];
+
+                // shift earlier gap-sorted elements up until
+                // the correct location for a[i] is found
+                int j;
+                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
+                    arr[j] = arr[j - gap];
+
+                // put temp (the original a[i]) in its correct
+                // location
+                arr[j] = temp;
+            }
+        }
+        return 0;
+    }
+
+    // Driver method
+    public static void main(String args[])
+    {
+        int arr[] = {12, 34, 54, 2, 3};
+        System.out.println("Array before sorting");
+        printArray(arr);
+
+        ShellSort ob = new ShellSort();
+        ob.sort(arr);
+
+        System.out.println("Array after sorting");
+        printArray(arr);
+    }
+} 
+/*This code is contributed by Rajat Mishra */