Java skiplist实现优化

时间:2015-11-26 16:02:56

标签: java optimization skip-lists

我在java中使用skiplist实现。基本上一切正常,但put方法执行时间太长。这是我的代码,我一直在浏览教程并查看一些人的代码,我似乎没有看到问题出在哪里(如果你测量的是将100000个随机元素放在一起需要多长时间才能工作)。

public class SkipList<K,V> {

    private final SkipListItem<K,V> head;
    private int currentLevel = 0;
    private static final Random random = new Random();
    private int height = 0;

    public SkipList() {
        this.head = new SkipListItem<>(null, null);
    }

    public V put(K key, V value) {
        return this.put(key, value, null, 0);
    }

    private V put(K key, V value, SkipListItem<K,V> previous, int level) {
        if(level > this.height) {
            for(int i=0,s=level-this.height ; i<s ; ++i) {
                this.addHeadItem();
            }
        }
        SkipListItem<K,V> addedItem = new SkipListItem<>(key, value);
        SkipListItem<K,V> insertAfter = this.findLowerItem(key, level);
        addedItem.setPrevious(insertAfter);
        if(insertAfter.getNext() != null) {
            insertAfter.getNext().setPrevious(addedItem);
            addedItem.setNext(insertAfter.getNext());
        }
        insertAfter.setNext(addedItem);
        if(previous != null) {
            addedItem.setBelow(previous);
            previous.setAbove(addedItem);
        }

        return (SkipList.random.nextBoolean()) ? this.put(key, value, addedItem, level+1) : value ;
    }

    private void addHeadItem() {
        SkipListItem<K,V> item = this.head;
        while(item.getAbove() != null) {
            item = item.getAbove();
        }
        SkipListItem<K,V> newHead = new SkipListItem<>(null,null);
        item.setAbove(newHead);
        newHead.setBelow(item);
        ++this.height;
    }

    private SkipListItem<K,V> findLowerItem(K key) {
        return this.findLowerItem(key,0);
    }

    private SkipListItem<K,V> findLowerItem(K key, int level) {
        SkipListItem<K,V> currentItem = this.head;
        for(int i=0 ; i<level ; ++i) {
            currentItem = currentItem.getAbove();
        }
        while(  currentItem.getNext() != null &&
                currentItem.getNext().getKey() != null &&
                currentItem.getNext().compareTo(key) < 0) {
            currentItem = currentItem.getNext();
        }
        return currentItem;
    }
    //...some other functions...
}

任何想法为什么花了这么长时间?

1 个答案:

答案 0 :(得分:0)

乍一看,无论何时插入新项目,您都可以通过整个列表找到该位置。这会导致线性复杂性,因此最后插入n项需要n*n次操作。

特别是在你的情况下,最终的数字是10亿次操作已经相当复杂,所以我可以想象这将花费几分钟来填充。