private void rebalance() {
        // Fictitious names for now
        int leftIndex = 0;
        int rightIndex = 0;
        int parentIndex = getParentIndex(getParentIndex(array.getLastPosition()));

        while (needRebalance()) {

            leftIndex = getLeftChildIndex(parentIndex);
            rightIndex = getRightChildIndex(parentIndex);

            if (height(leftIndex) - height(rightIndex) > 1) {
                // Left branch is two elements longer
                rotateRight(parentIndex);

            } else if (height(leftIndex) - height(rightIndex) < -1) {
                // Right branch is two elements longer
                rotateLeft(parentIndex);

            }

            if (parentIndex > 0) {
                // If the rotation was unsuccessful, go one layer higher
                parentIndex = getParentIndex(parentIndex);
            } else {
                rebalance();
            }

        }
    }