private E removeEntry(BinaryNode node, E entry, BinaryNode father) { E result = null; if (entry.compareTo(node.getData()) == 0) { result = node.getData(); decSize(); if (!hasLeft(node)) { // der er ikke et venstre barn if (node.equals(father.getLeft())) { father.setLeft(right(node)); } else { father.setRight(right(node)); } } else if (!hasRight(node)) { // der er ikke et højre barn if (node.equals(father.getLeft())) { father.setLeft(left(node)); } else { father.setRight(left(node)); } } else { // der er både højre og venstre barn} removeNodeTwoChildren(node); } } else if (entry.compareTo(node.getData()) < 0) { if (hasLeft(node)) removeEntry((BinaryNode) left(node), entry, node); } else { if (hasRight(node)) removeEntry((BinaryNode) right(node), entry, node); } return result; }
public static <E extends Comparable<? super E>> List<E> quickSort(List<E> arr) { if (!arr.isEmpty()) { E pivot = arr.get(0); // This pivot can change to get faster results List<E> less = new LinkedList<>(); List<E> pivotList = new LinkedList<E>(); List<E> more = new LinkedList<E>(); // Partition for (E i : arr) { if (i.compareTo(pivot) < 0) less.add(i); else if (i.compareTo(pivot) > 0) more.add(i); else pivotList.add(i); } // Recursively sort sublists less = quickSort(less); more = quickSort(more); // Concatenate results less.addAll(pivotList); less.addAll(more); return less; } return arr; }
private E findStartingNodeForDeletion(E element) { if (root == null) return null; TreeNode<E> parent = null; TreeNode<E> current = root; while (current != null) { if (element.compareTo(current.element) < 0) { parent = current; current = current.left; } else if (element.compareTo(current.element) > 0) { parent = current; current = current.right; } else break; } if (current == null) return null; if (current.left == null) { if (parent == null) { return null; } else { return parent.element; } } else { TreeNode<E> parentOfRightMost = current; TreeNode<E> rightMost = current.left; while (rightMost.right != null) { parentOfRightMost = rightMost; rightMost = rightMost.right; } return parentOfRightMost.element; } }
/** * Compare the element to the node.userObject. If its smaller add to the leftChild. If bigger add * to the rightChild. This is done via recursion. * * <p>If the element already exists do nothing. Its a search tree so duplicates are not allowed. * * @param element * @param node */ private void insert(E element, BKnoop<E> node) { bumpCounter(); // System.out.println("Node :" + node.get()); // System.out.println("Element :" + element); int comp = element.compareTo(node.get()); // System.out.println("comp: " + comp); if (comp <= -1) { // System.out.println("Comp -1"); if (node.getLeftChild() == null) { // System.out.println("Insert left"); node.insert(new BKnoop<E>(element), BKnoop.LEFT); } else { insert(element, node.getLeftChild()); } } else if (comp >= 1) { // System.out.println("Comp 1"); if (node.getRightChild() == null) { // System.out.println("Insert right"); node.insert(new BKnoop<E>(element), BKnoop.RIGHT); } else { insert(element, node.getRightChild()); } } }
public void add(E newData) { innerList.add(newData); // 如果放进来的是第一个元素,那就是根节点,无需其它才做 if (innerList.size() == 1) { } else { int currentIndex = innerList.size() - 1; int parentIndex = (currentIndex - 1) / 2; E parent = innerList.get(parentIndex); while (currentIndex != 0 && parent.compareTo(newData) < 0) { E tmp = parent; innerList.set(parentIndex, innerList.get(currentIndex)); innerList.set(currentIndex, tmp); currentIndex = parentIndex; parentIndex = (currentIndex - 1) / 2; parent = innerList.get(parentIndex); } } System.out.println("add执行完毕,当前的数组:"); for (E e : innerList) { System.out.print(e + " "); } System.out.println(""); }
/** * Recursive delete method. post: The item is equal to the deleted item as it was stored in the * tree or null if the item was not found. * * @param root The root of the current subtree * @param target The item to be deleted * @return The modified root that does not contain the item */ private Node<E> delete(Node<E> root, E target) { if (root == null) { deleteReturn = null; return root; } int r = target.compareTo(root.data); if (r < 0) { root.left = delete(root.left, target); return root; } else if (r > 0) { root.right = delete(root.right, target); return root; } else { deleteReturn = root.data; if (root.left == null) { return root.right; } else if (root.right == null) { return root.left; } else { if (root.left.right == null) { root.data = root.left.data; root.left = root.left.left; return root; } else { root.data = findLargestChild(root.left); return root; } } } }
// public static <E extends Comparable<E>> E max(List<E> list) { public static <E extends Comparable<? super E>> E max(List<? extends E> list) { E candidate = list.get(0); for (E element : list) { if (candidate.compareTo(element) < 0) { candidate = element; } } return candidate; }
@Override public E next() { int iComp = _csr.compareTo(getRightEndpoint()); if (iComp > 0 || (!isRightClosed() && iComp == 0)) { throw new NoSuchElementException(); } E ret = _csr; _csr = _csr.nextInSequence(getStep(), getUnit()); return ret; }
/** * Inserts the specified element into this delay queue. * * @param e the element to add * @return <tt>true</tt> * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { E first = q.peek(); q.offer(e); if (first == null || e.compareTo(first) < 0) available.signalAll(); return true; } finally { lock.unlock(); } }
void moveUp(int pos, E node) { while (pos > 0) { int parent = (pos - 1) >> 1; E parentNode = h.get(parent); if (node.compareTo(parentNode) >= 0) { break; } h.set(pos, parentNode); pos = parent; } h.set(pos, node); }
protected void percolateUp(int leaf) { // pre: 0<=leaf<size // post: moves node at index lead up to appropiate position int parent = parent(leaf); E value = data.get(leaf); while (leaf > 0 && (value.compareTo(data.get(parent)) < 0)) { data.set(leaf, data.get(parent)); leaf = parent; parent = parent(leaf); } data.set(leaf, value); }
/** * Recursive find method. * * @param root The local subtree's root * @param target The object being sought * @return The object, if found, otherwise null */ private E find(Node<E> root, E target) { if (root == null) { return null; } int compresult = target.compareTo(root.data); if (compresult == 0) { return root.data; } else if (compresult < 0) { return find(root.left, target); } else return find(root.right, target); }
/** * @param element: The element to insert into the Tree * @param temp: The AVLNode to evaluate for recursive insertion * <p>This method recursively traverses the Tree, inserting the element at the appropriate * spot and incrementing the balance factors for the subtrees as it evaluates. The Tree will * then recursively rebalance as necessary. */ private void insert(E element, AVLNode<E> temp) { if (this.rootAbove.getLeft() == null) { this.rootAbove.setLeftNode(new AVLNode<E>(element)); return; } // travel left or right based on the // comparison of element to temp.element // remember that left means that element <= temp.element // and right means element > temp.element int compare = element.compareTo(temp.getElement()); // travel to the left of the Tree, inserting // if the bottom has been reached if (compare <= 0) { // System.out.println(temp.getLeft()); if (temp.getLeft() == null) { temp.setLeft(element); return; } insert(element, temp.getLeft()); } // otherwise, travelling to the right of the Tree, // inserting if the bottom has been reached else { if (temp.getRight() == null) { temp.setRight(element); return; } insert(element, temp.getRight()); } // if the root is being evaluated it, rotate if necessary if (temp == rootAbove.getLeft()) { rotate(rootAbove.getLeft(), rootAbove); } // otherwise, rotate the left and right subtrees // as necessary if (temp.getLeft() != null) { rotate(temp.getLeft(), temp); } if (temp.getRight() != null) { rotate(temp.getRight(), temp); } } // end insert
/** * @param element: The element to remove from the AVLTree * @param temp: The root node of the subtree * <p>This method recursively traverses the AVLTree based on the ordering of the element with * respect to the Tree's elements. If the element is not found, then nothing happens. * Otherwise, the element is removed, and either the far-right element on its left child or * the far left element on its right child replaces it. * */ private void remove(E element, AVLNode<E> temp) { if (temp == null) return; int compare = 0; if (temp != rootAbove) compare = element.compareTo(temp.getElement()); boolean direction = (compare > 0 && temp != rootAbove); AVLNode<E> child = direction ? temp.getRight() : temp.getLeft(); if (child == null) return; // if the root is perfectly balanced, slide the left Node up // and reinsert the left.right element if necessary if (temp == rootAbove && child.getBalance() == 0 && child.getElement().equals(element)) { AVLNode<E> newRoot = child.getLeft(); if (newRoot == null) { rootAbove.setLeftNode(null); return; } else { enactRemoval(temp, child, false); return; } } // if the element is found and the root is not // perfectly balanced, remove it using enactRemoval() else if (element.compareTo(child.getElement()) == 0) { enactRemoval(temp, child, direction); } // otherwise, recursively traverse the tree else { remove(element, child); } }
/** * @param element: The element to search for in the AVLTree * @return boolean: true if the element is found, false otherwise * <p>The contains method simply traverses the binary search tree based on element's relation * to the AVLNodes in the Tree until a match is found or it hits the bottom of the Tree. */ public boolean contains(E element) { AVLNode<E> temp = rootAbove.getLeft(); while (temp != null) { if (temp.getElement().equals(element)) return true; int balance = element.compareTo(temp.getElement()); temp = (balance < 0) ? temp.getLeft() : temp.getRight(); } return false; }
public AVLNode<E> find(E element) { AVLNode<E> temp = rootAbove.getLeft(); while (temp != null) { if (temp.getElement().equals(element)) return temp; int balance = element.compareTo(temp.getElement()); temp = (balance < 0) ? temp.getLeft() : temp.getRight(); } return null; }
public boolean delete(E element) { if (root == null) return false; TreeNode<E> parent = null; TreeNode<E> current = root; while (current != null) { if (element.compareTo(current.element) < 0) { parent = current; current = current.left; } else if (element.compareTo(current.element) > 0) { parent = current; current = current.right; } else break; } if (current == null) return false; if (current.left == null) { if (parent == null) { root = current.right; } else { if (element.compareTo(parent.element) < 0) parent.left = current.right; else parent.right = current.right; balancePath(parent.element); } } else { TreeNode<E> parentOfRightMost = current; TreeNode<E> rightMost = current.left; while (rightMost.right != null) { parentOfRightMost = rightMost; rightMost = rightMost.right; } current.element = rightMost.element; if (parentOfRightMost.right == rightMost) parentOfRightMost.right = rightMost.left; else parentOfRightMost.left = rightMost.left; balancePath(parentOfRightMost.element); } size--; return true; }
/** * Update the path from node down to the node containing element. Since it is guaranteed there is * a path between these two arguments, node should never become null. * * @param node the root of some subtree, originally the root of the subtree whose node was * removed. * @param element the element stored at the end of the path to be updated. This element was the * parent to the value t hat supplied the replacement value for a node during a remove() * operation. */ private AVLNode<E> updatePath(AVLNode<E> node, E element) { int compareResult = element.compareTo(node.getElement()); if (compareResult == 0) { // reached the end of the path node = fixSubtreeRootedAt(node); } else if (compareResult < 0) { node.leftChild = updatePath((AVLNode<E>) node.leftChild, element); node = fixSubtreeRootedAt(node); } else if (compareResult > 0) { node.rightChild = updatePath((AVLNode<E>) node.rightChild, element); node = fixSubtreeRootedAt(node); } return node; }
/** * Determine if this tree contains <tt>element</tt>. * * @param element the element we are looking for in the tree. * @return <tt>true</tt> if <tt>element</tt> is found in this tree, <tt>false</tt> otherwise. */ protected boolean contains(BSTNode<E> node, E element) { if (node == null) { return false; } int compareResult = element.compareTo(node.getElement()); if (compareResult < 0) { return contains(node.leftChild, element); } else if (compareResult > 0) { return contains(node.rightChild, element); } else { return true; } }
/** * O(N) Add an item to this set. <br> * item != null * * @param item the item to be added to this set. item may not equal null. * @return true if this set changed as a result of this operation, false otherwise. */ public boolean add(E item) { if (item == null) throw new IllegalArgumentException("Illegal Parameter: item cannot be null"); if (!(this.contains(item))) { int index = 0; boolean found = false; while (index < myCon.size() && !found) { if (item.compareTo(myCon.get(index)) <= 0) found = true; else index++; } myCon.add(index, item); return true; } return false; }
private void checkArgs(E left, E right) { if (left == null) { throw new IllegalArgumentException( "Non-null value expected for left endpoint. Use BigIntegerInterval for an interval with an unbounded endpoint."); } if (right == null) { throw new IllegalArgumentException( "Non-null value expected for right endpoint. Use BigIntegerInterval for an interval with an unbounded endpoint."); } if (left.compareTo(right) > 0) { throw new IllegalArgumentException( "The left endpoint is greater than the right endpoint: [" + left + ", " + right + "]"); } }
@Override public E remove(E entry) { E result = null; if (!isEmpty()) { if (root().getData().compareTo(entry) == 0) { // det er roden der skal slettes result = root().getData(); decSize(); removeRoot(); } else if (entry.compareTo(root().getData()) < 0) { result = removeEntry((BinaryNode) left(root()), entry, (BinaryNode) root()); } result = removeEntry((BinaryNode) right(root()), entry, (BinaryNode) root()); } return result; }
void moveDown(int pos, E node) { int half = h.size() >> 1; while (pos < half) { int child = 2 * pos + 1; if (child < h.size() - 1 && h.get(child).compareTo(h.get(child + 1)) > 0) { ++child; } if (node.compareTo(h.get(child)) <= 0) { break; } h.set(pos, h.get(child)); pos = child; } h.set(pos, node); }
@Override public E getFromRight(int iStepIndex) { if (iStepIndex < 0) { throw new IllegalArgumentException("Step index must be >= 0: " + iStepIndex); } if (!isRightClosed()) { iStepIndex++; } E value = getRightEndpoint().previousNthInSequence(getStep(), getUnit(), iStepIndex); int iComp = value.compareTo(getLeftEndpoint()); if (isLeftClosed() ? iComp >= 0 : iComp > 0) { return value; } return null; }
/** * Recursive add method. post: The data field addReturn is set true if the item is added to the * tree, false if the item is already in the tree. * * @param root The local root of the subtree * @param item The object to be inserted * @return The new local root that now contains the inserted item */ private Node<E> add(Node<E> root, E item) { if (root == null) { addReturn = true; return new Node<E>(item); } int r = item.compareTo(root.data); if (r == 0) { addReturn = false; return root; } else if (r < 0) { root.left = add(root.left, item); return root; } else { root.right = add(root.right, item); return root; } }
@Override public PriorityQueue<E> enqueue(E element) { if (isEmpty()) { head = element; return new LinkedList<>(element); } if (head.compareTo(element) == -1) { tail = tail.enqueue(element); } else { tail = new LinkedList<>(head, tail.copy()); head = element; } return new LinkedList<>(head, tail.copy()); }
@Override void insert(E e) { if (keys.indexOf(e) != -1) { throw new RuntimeException("The element already exists."); } int index = childIndexOf(e); if (children.get(index).isFull()) { childSplit(index); if (e.equals(keys.get(index))) { throw new RuntimeException("The element already exists."); } else if (e.compareTo(keys.get(index)) < 0) { children.get(index).insert(e); } else { children.get(index + 1).insert(e); } } else { children.get(index).insert(e); } }
protected FHthreadedNode<E> find(FHthreadedNode<E> root, E x) { int compareResult; if (root == null) return null; while (true) { if (root == null) return null; compareResult = x.compareTo(root.data); if (compareResult < 0) { if (root.lftThread) return null; root = root.lftChild; } else if (compareResult < 0) { if (root.rtThread) return null; root = root.rtChild; } else break; } return root; // found }
/** * Add <tt>element</tt> to the tree. * * @param parent parent of <tt>node</tt> * @param node root of subtree to which element is to be added * @param element the element to be added to the tree * @throws SearchTreeException if node is found in the tree */ protected BSTNode<E> add(BSTNode<E> parent, BSTNode<E> node, E element) { if (node == null) { // base case node = new AVLNode(element); node.parent = parent; } else { // recursive case int compareResult = element.compareTo(node.getElement()); if (compareResult < 0) { node.leftChild = add(node, node.leftChild, element); } else if (compareResult > 0) { node.rightChild = add(node, node.rightChild, element); } else { throw new SearchTreeException("Duplicate element: " + element.toString()); } // now do height/balance updates and possible // subtree fixes node = fixSubtreeRootedAt((AVLNode<E>) node); } return node; }
/** @return {@code true} if this set was modified by the operation */ @Override public boolean add(E element) { if (size() < maxElementCount) { // if we are not yet at the limit, just add return super.add(element); } Comparator<? super E> comparator = comparator(); E last = last(); int compareTo; if (comparator == null) { compareTo = element.compareTo(last); } else { compareTo = comparator.compare(element, last); } if (compareTo < 0) { // if this element is smaller than the largest one remove(last); // remove the last return super.add(element); // and add this; sorting will be ensured by TreeSet } else { // otherwise, no changes done return false; } }