Array (0 Empty) P n/2, LC 2n, RC 2n+1 Quick Sort
Array (0 Empty) P n/2, LC 2n, RC 2n+1 Quick Sort
Quick Sort
public void add(E node) { h.add(node); moveUp(h.size() - 1); } void moveUp(int pos) { while (pos > 0) { int parent = (pos - 1) / 2; if (h.get(pos).compareTo(h.get(parent)) >= 0) { break; } Collections.swap(h, pos, parent); pos = parent; }} public E remove() { E removedNode = h.get(0); E lastNode = h.remove(h.size() - 1); if (!h.isEmpty()) { h.set(0, lastNode); moveDown(0); } return removedNode; } void moveDown(int pos) { while (pos < h.size() / 2) { int child = 2 * pos + 1; if (child < h.size() - 1 && h.get(child).compareTo(h.get(chil d + 1)) > 0) { ++child; } if (h.get(pos).compareTo(h.get(child)) <= 0) { break; } Collections.swap(h, pos, child); /**This method returns the pivot (index as int) * that partitions the list into two. Takes * two ints - low and high indices of the current * partition.*/ public int partition(int left, int right){ int i = left, j = right; int tmp; int pivot = list.get((left+right)/2); while(i <= j){ while(list.get(i) < pivot){i++;} while(list.get(j) > pivot){j--;} if(i <= j){ tmp = list.get(i); list.set(i, list.get(j)); list.set(j, tmp); i++;j--; } } return i; }
/** This void method takes the least and highest * index of the list and uses the quick sort * algorithm to sort the unsorted arraylist of * integers.*/ public void quickSort(int left, int right) { if(right>0){ int index = partition(left, right); if(left < index -1) quickSort(left, index -1); if(index<right) quickSort(index, right);
/** This void method takes the least, highest and the * middle index of the current list. It also takes the * temporary list as its parameter */ private void merge(int left, int middle, int right, ArrayList<Integer> tempList){ int indexLeft = left; int indexRight = middle+1; int target = left; //copy both pieces into tempList for(int i = left; i <= right; i++){ tempList.add(i, list.get(i)); } //list is the original list in the superclass here //merge values while there are elements left in both halves. while(indexLeft <= middle && indexRight <= right){ if(tempList.get(indexLeft) < tempList.get(indexRight)){ list.set(target, tempList.get(indexLeft)); //edits the original list indexLeft++; }else{ list.set(target, tempList.get(indexRight)); indexRight++; } target++; } //move if any remaining elements from the left half. while(indexLeft <= middle){ list.set(target, tempList.get(indexLeft)); indexLeft++; target++; } //move if any remaining elements from the right half while(indexRight <= right){ list.set(target, tempList.get(indexRight)); indexRight++; target++;
Merge Sort
/** This void method takes the lowest and highest indices * of the current list and a copy of the original list as * its parameter. It then calls the merge() method that * merges the sorted partiotioned lists.*/ public void mergeSort(int left, int right, ArrayList<Integer> tempList){ if(left<right){ int middle = (right+left)/2; mergeSort(left, middle, tempList); //sort the left half of the array mergeSort(middle+1, right, tempList); //sort the right half of the array merge(left, middle, right, tempList);
Insertion //starts at 2nd position and checks with the ones in the left and swaps until it cannot. public void sort(ArrayList list){ for(int i = 1; i<list.size(); i++){ int j=i; while(j>0 && list.get(j) < list.get(j-1)){ int temp = list.get(j); list.set(j, list.get(j-1)); list.set(j-1, temp); j--; } } Return list; } Selection //runs through the entire list every time starting from the first index and finds the smallest and places it in the current index. public void sort(ArrayList list){ for(int i = 0; i<list.size(); i++){ int smallerIndex = i; int tmp = 0; int smallValue = list.get(i); for(int j = i+1; j<list.size(); j++) { if(smallValue > list.get(j)){ smallValue = list.get(j); smallerIndex = j; } } list.set(smallerIndex, list.get(i)); list.set(i, smallValue); }
} Tree traversals: In order, postorder, preorder, level order public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); System.out.print(node.value + " "); traverseInOrder(node.right); } TwoThreeTree traverseInOrder(TwoThreeTreeNode< K,E> node){ if (node.left != null) traverseInOrder(node.left); if (node.small != null ) System.out.println(node.small); if (node.middle != null) traverseInOrder(node.middle); if (node.large != null) System.out.println(node.large); if (node.right != null) traverseInOrder(node.right); } public void preOrder(Node node) { if (node != null) { System.out.print(node.value + " "); preOrder(node.left); preOrder(node.right); } } public void postOrder(Node node){ if (node != null) { postOrder(node.left); postOrder(node.right); System.out.print(node.value + " "); } } public void levelOrder(Node n){ LinkedList<Node> q = new LinkedList<Node>(); q.add(n); while (!q.isEmpty()) { Node node = q.removeFirst(); //pop off the top element System.out.print(node.value + " "); //enqueue the children Node left = node.left; if ( left != null ) { q.add(left); } //similar for right Node right = node.right; if(right != null){ q.add(right); } } }
ublic class BinaryNode<K extends Number & Comparable, V> implements Comparator<BinaryNode>{} public class TwoThreeTree<K extends Number & Comparable, E>{} public void remove(int key, Node node){ //find the node and remove Node removed = null; Binary tree find(iterative) while(node != null){ if(node.value == key){ public boolean find(Node node, int key){ removed = node; while(node != null){ break; if(node.value == key) } return true; else if(key < node.value) else if(node.value < key) node = node.left; return find(node.right, key); else if(key > node.value) else if(node.value > key) node = node.right; return find(node.left, key); } } replacesmallestRight(removed); return false; } } public void replacesmallestRight(Node removed){ if(removed.right == null && removed.left != null){ removed = removed.left; return; } if(removed.right == null) return; Node r = removed.right; if(r != null){ while(r.left != null){ r = r.left; } } removed.value = r.value; r.parent.left = null;//set the //leaf node to null }
Graph Stuffs
* This method finds the shortest path from a given node to the destination node and stores the node keys in an arraylist. * It uses what is called the working list algorithm in which we have two lists of nodes - seen, and worklist(started * but not completeley processed). We use the Depth Fisrst traversal to move around the graph to find the path. ie, our worklist * would simulate a Queue. * @param K1 The key of the source node * @param K2 The key of the destination node * @return path Arraylist that gives the sequence of node keys from the source node to the destination node. * This would be the shortest path. */ public ArrayList<K> findShortestPath(K k1, K k2){ this.resetVisited(); ArrayList<K> path = new ArrayList<K>(); ArrayList<DirectedGraphNode> seen = new ArrayList<DirectedGraphNode>(); //the nodes processed private boolean insert(Node node, int value)new ArrayList<DirectedGraphNode>(); //our worklist ArrayList<DirectedGraphNode> worklist = { ////create one adding the given source node to the worklist. The node must be found to do that,so that we could look into start off by if node is null (rootnode == nodes //ifits neighboring null){ sequentially. We also find the destination node, while we're at it rootnode = new Node(value); DirectedGraphNode source = null; rootnode.setParent(null); DirectedGraphNode goal = null; } Integer givenKey1 = new Integer((Integer)k1); //do this once you have root Integer givenKey2 = newaInteger((Integer)k2); - set the start node weight to 0, all others to infinity. if (value < node.value) { //set all node's seen boolean to false before starting, and also - place the start node in your worklist. if (node.left != null) { find the - each time in your while loop (loop runs while your insert(node.left, value); // two nodes we need -start and goal worklist is not empty, or you've moved the goal node to return true; for(DirectedGraphNode node: nodes){ the "seen" list) , find the node that has the least weight } else { node.seen = false; among the given ones at the time and move it to the node.left = new new Integer((Integer)node.getKey()); Integer nodeKey = Node(value, node); "seen" list. Subsequently move that node's neighbors into } if(nodeKey.compareTo(givenKey1) == 0) the worklist if they are not already there. } source (value > node.value) { else if = node; - if your worklist becomes empty, it means there is no if (node.right != null) { if(nodeKey.compareTo(givenKey2) == 0) path to the goal node. insert(node.right, value); goal = node; - take some care to mark the nodes you've already visited } return true; so that you do not have duplicate nodes in your worklist, } else { node.right = new Node(value, // return if one of the nodes are not found node); or any "seen" node for that matter. seen nodes are the } if(source == null || goal == null){ ones for which you already have the shortest path. } return true; } System.err.println("The given nodes do not exist!"); return path; //returns empty path meaning no path exists. } System.out.println("\n\n Finding shortest path from: " + source.getKey() + "\t to \t"+ goal.getKey()); // add the source node to the seen as we already know its shortest path, add its neighbors to worklist as we... // ...know "a" path worklist.add(source); DirectedGraphNode leastNode = null;// we'll subsequently add its neighbors to the worklist source.parent = null; source.resetToStart(); while(seen.contains(goal) == false && worklist.size() != 0){ // run the loop until we know the shortest path to the goal node // now find the node with the smallest weight from the nodes in the worklist and add it to "seen" Double leastWeight = Double.MAX_VALUE; // the following loop will select the node with least weight. selects the first instance if multiples exist. for(DirectedGraphNode worklistNode: worklist){ if(worklistNode.weight < leastWeight){ } leastWeight = worklistNode.weight; //add the current node's neighbor to the leastNode = worklistNode; worklist,but first check if it is already in the } worklist } if(worklist.contains(neighbor) == false && worklist.remove(leastNode); neighbor.seen == false){ // update the parent pointer of the leastNode a.k.a the currentNode worklist.add(neighbor); and add it to the "seen" list } // leastNode.parent = currentNode; } if(leastNode != null){ } seen.add(leastNode); //print the shortest path cost as well as find the leastNode.seen = true; path with keys and return the keys in the arraylist. } if(goal.weight == Double.MAX_VALUE) //this iterates through the neighbors of the leastNode System.err.println("Shortest path cost is for(Edge e: (LinkedList<Edge>)leastNode.outgoing){ infinity. (No path exists!)"); DirectedGraphNode neighbor = e.getNode(); else //update the neighbor's cumilative weight by checking the current and the new weight System.out.println("Shortest path cost is: " + neighbor.temp = e.getWeight() + leastNode.weight; goal.weight); if(neighbor.temp < neighbor.weight){ } neighbor.parent = leastNode; neighbor.weight = neighbor.temp; Top Sort
* This method generates the topological sort of the given graph. For longest path, initialize the weights to We start off by calculating the indegree for zero, then in the graph. Any node that happens to have an * every node If weight zero edge weight > weight P, indegree of N + will go into a queue. We then dequeue * the first element from + queue, add that weight P = weight N theedge weight; node's key to the topological sort array, and then decrease the indegree * of the nodes in its adjacency list by one, and if that happens to /**This method uses the binary search algorithm to be 0 then, we enqueue them right there on the spot. find we do that until our queue is passed as a * the first index of the integer empty. parameter. IttopSort theadditionalof keys of the topologically sorted * @return takes two arraylist parameter * the nodes least index and the highest index of the */ list. It operates on the sorted list. Return type is int public number is not in the list). (-1 if the ArrayList<K> topSort(){ */ resetVisited(); LinkedList<DirectedGraphNode> sortQueue = new LinkedList<DirectedGraphNode> (); public int binarySearch(int n, int start, int end){ ArrayList<K> topSort = new ArrayList<K>(); if(end<0) //set the indegrees of the nodes, and enqueue the ones with 0 return -1; indegree int middleindex = start + (end - start)/2; for(DirectedGraphNode node: nodes){ //System.out.println(list.get(end)); node.setIndegree(); if(n<list.get(start) || n>list.get(end)){ if(node.indegree == 0) return -1; sortQueue.add(node); }else if(list.get(middleindex)>n){ } return binarySearch(n, start, middleindex-1); //This loop runs as long as the worklist of nodes with 0 indegree }else if(list.get(middleindex)<n){ is not empty return binarySearch(n, middleindex+1, end); while(!sortQueue.isEmpty()){ }else { DirectedGraphNode return middleindex; currentNode = sortQueue.removeFirst(); } topSort.add((K)currentNode.key);//add the key of the current node } for(Edge out: (LinkedList<Edge>)currentNode.outgoing){ out.getNode().indegree--; //decrease the indegree counter for each of such neighboring nodes if(out.getNode().indegree == 0) sortQueue.add(out.getNode()); } } If the length of the sorted array is not equal, there must be cycles Dijkstras algorithm in the graph. Foreach node set distance[node] = HIGH SettledNodes = empty UnSettledNodes = empty Add sourceNode to UnSettledNodes distance[sourceNode]= 0 while (UnSettledNodes is not empty) { evaluationNode = getNodeWithLowestDistance(UnSettledNodes) remove evaluationNode from UnSettledNodes add evaluationNode to SettledNodes evaluatedNeighbors(evaluationNode) } getNodeWithLowestDistance(UnSettledNodes){ find the node with the lowest distance in UnSettledNodes and return it } evaluatedNeighbors(evaluationNode){ Foreach destinationNode which can be reached via an edge from evaluationNode AND which is not in SettledNodes { edgeDistance = getDistance(edge(evaluationNode, destinationNode)) newDistance = distance[evaluationNode] + edgeDistance if (distance[destinationNode] > newDistance ) { distance[destinationNode] = newDistance add destinationNode to UnSettledNodes
import java.util.*; Public class WordGraph{ private HashMap<String, WordNode> map = new HashMap<String, WordNode>(); /*PUBLIC METHODS*/ public void add(WordGraph.WordNode node){ int difference = 0; Iterator nodes = map.values().iterator(); WordNode nextNode = null; while(nodes.hasNext()){ nextNode = (WordNode)nodes.next(); String word_added = node.getWord(); difference = getDifference(word_added, nextNode.getWord()); //join the nodes of difference one if(difference == 1){ nextNode.related.add(node); node.related.add(nextNode); } //join nodes for which one word is a part of the other. if(word_added.contains(nextNode.word)){ nextNode.partOf.add(node); //current node's word is a part of the added word }else if(nextNode.word.contains(word_added)){ node.partOf.add(nextNode);//added word is a part of the current node's word } } when removing, simply do hashmap.get(key(string))
// declares an
File handlng
public void run() throws IOException { InputStreamReader in = new InputStreamReader(System.in); BufferedReader bfr = new BufferedReader(in); System.out.println("Type your file name: "); String filename = null; try{ filename = bfr.readLine(); }catch(IOException e){ System.err.println(e); } FileReader fr = null; File f = null; BufferedReader bffr = null; try{ f = new File(filename); fr = new FileReader(filename); bffr = new BufferedReader(fr); }catch(java.io.FileNotFoundException e){ System.err.println("File not Found!"); } //get the filename String input = null; if (bffr != null) { input = bffr.readLine(); } //get the words from the file Scanner sc = null; try{ sc = new Scanner(f); //creating the scanner for the file object. }catch(IOException e){ System.err.println("Error accessing the file: " + e); } System.err.println("Mapping the textfile...");
try{ //The following nested loop parses each line of the file and looks for integers until the end of file is reached. int line = 0; String nextLine = null; while(sc.hasNextLine()){ line++; nextLine = sc.nextLine(); String[] line_words = nextLine.split("([.,!?:;\"-] +|\\s)"); String someWord; for(int i = 0; i < line_words.length ; i++){ someWord = line_words[i]; // System.out.println(someWord + line); //this prints the integers as it is found graph.add(new WordGraph.WordNode(someWord, filename, line)); } } sc.close(); }catch(java.lang.Exception e){ System.err.println(e); } System.out.println("Type the word you wish to find: "); String query = bfr.readLine(); System.err.println(graph.findWords(query)); }