【问题标题】:Ordered insertion working sporadically with primitive types & strings有序插入偶尔使用原始类型和字符串
【发布时间】:2011-11-18 01:42:59
【问题描述】:

对于一项任务,我们被要求在 Java 中将 LinkedLists 的有序和无序版本实现为 Bags。有序版本将简单地扩展无序实现,同时覆盖插入方法。

插入功能的排序工作......有点。给定一个测试数组

String[] testArray= {"z","g","x","v","y","t","s","r","w","q"};

输出是

q w r s t y v x g z 

应该是什么时候

g q r s t v w x y z

但是,当元素的值没有混淆时,排序可以正常工作。例如,我最初使用上面的testArray[],将字母颠倒,并且顺序完全符合应有的顺序。

我的添加功能是

@Override
public void add(E e){
    Iter iter= new Iter(head.prev);
    int compValue;
    E currentItem= null;

    //empty list, add at first position
    if (size < 1)
        iter.add(e);

    else {

        while (iter.hasNext()){
            currentItem= iter.next(); //gets next item

            //saves on multiple compareTo calls
            compValue= e.compareTo(currentItem); 

            //adds at given location
            if (compValue <= 0)
                iter.add(e, iter.index);

            else //moves on
                currentItem= iter.next();
        }
    }
}

迭代器功能实现为

//decided to use iterator to simplify method functionality
protected class Iter implements Iterator<E>, ListIterator<E>{
    protected int index= 0;
    protected Node current= null;

//Sets a new iterator to the index point provided
    public Iter(int index){
        current= head.next;
        this.index=0;
        while (index > nextIndex()) //moves on to the index point
            next();
    }

public void add(E e, int index){
        size++;

        Iter iterator= new Iter(index);

        Node node= new Node();
        Node current= iterator.current.prev;

        node.next= current.next;
        node.prev= current;
        node.next.prev= node;
        node.prev.next= node;

        node.item= e;
    }

就像现在一样,唯一使用的东西是原始类型。我知道对于对象,必须编写一个特定的可比较类,但在这种情况下,String 包含一个 compareTo() 方法,该方法应该给出正确的顺序。

碰巧,我的一个同学有类似的实现,并返回相同的结果。

使用自然排序,我该如何解决这个问题?

【问题讨论】:

    标签: data-structures comparable insertion-sort


    【解决方案1】:

    关于你的 add() 函数的三件事突然出现在我身上:

    1. 它应该在插入新值后立即退出循环;这实际上可能不是问题,但继续寻找效率低下
    2. 您在循环顶部调用 next_item,但如果未添加该值,则再次调用它
    3. 如果您的列表中只有 1 个值,并且您尝试添加一个大于列表中当前值的值,那么新值不会添加失败吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多