Esempio n. 1
0
    private void splitBranch(Comparator comparator, Object keyForNextNode, Node nextNode) {
      int halfSize = size / 2;

      int comparison = compareWithMidValues(comparator, keyForNextNode, halfSize);

      if (comparison == 0) {
        Branch nextBranch = create(capacity);

        // Copy half of the nodes from the original
        int copyFrom = keyOffset(halfSize);
        int length = arraySize() - copyFrom;
        shallowCopy(this, copyFrom, nextBranch, 1, length);
        nextBranch.size = halfSize;

        // Key from new node moved up.
        nextBranch.firstKey(keyForNextNode);
        nextBranch.setChild(0, nextNode);

        // clear out latter half...
        clearArrayFrom(keyOffset(halfSize));
        size = halfSize;

        // temporarily store the nextBranch for the parent.
        next(nextBranch);
      } else if (comparison < 0) {
        Branch nextBranch = create(capacity);

        // Copy half of the nodes from the original
        int copyFrom = keyOffset(halfSize);
        int length = arraySize() - copyFrom;
        shallowCopy(this, copyFrom, nextBranch, 1, length);
        nextBranch.size = halfSize;

        // Last key from first half moved up.
        nextBranch.firstKey(storedKey(halfSize - 1));
        nextBranch.setChild(0, getChild(halfSize * 2));

        // clear out latter half...
        clearArrayFrom(keyOffset(halfSize - 1));
        size = halfSize - 1;

        // Insert the new node
        insertNode(comparator, keyForNextNode, nextNode);

        // temporarily store the nextBranch for the parent.
        next(nextBranch);
      } else {
        Branch nextBranch = create(capacity);

        // Copy just under half of the nodes from the original
        int copyFrom = keyOffset(halfSize + 1);
        int length = arraySize() - copyFrom;
        shallowCopy(this, copyFrom, nextBranch, 1, length);
        nextBranch.size = halfSize - 1;

        // First key from second half moved up.
        nextBranch.firstKey(storedKey(halfSize));
        nextBranch.setChild(0, getChild((halfSize + 1) * 2));

        // clear out latter half...
        clearArrayFrom(keyOffset(halfSize));
        size = halfSize;

        // Insert the new node
        nextBranch.insertNode(comparator, keyForNextNode, nextNode);

        // temporarily store the nextBranch for the parent.
        next(nextBranch);
      }
    }