Putting elements into a sorted list

大城市里の小女人 提交于 2019-12-25 12:42:01

问题


Folks, my method needs to add a new element into already a sorted list, i.e. in a proper position. The point is the method has to add the objects in a diagonal sort. For example,

     board.set(1,1,11);
        board.set(2,4,33);
        board.set(3,4,66);
        board.set(3,2,44);
        board.set(3,3,55);
        board.set(1,4,88);
        board.set(0,2,77);
        board.set(0,5,99);
        board.set(2,1,22);

The result should be:

[(2,1,22), (3,2,44), (1,1,11), (3,3,55), (3,4,66), (0,2,77), (2,4,33), (1,4,88), (0,5,99)]

But my program prints this:

[(3,4,66), (3,3,55), (3,2,44), (2,4,33), (2,1,22), (1,4,88), (1,1,11), (0,5,99), (0,2,77)]

i.e. it does not put the objects into the proper positions.

I have a LinkedList<RowColElem<T>>leftDiagSeq where the objects are added and put into a proper position "on the go". What is my code missing?

NOTE: Im not allowed to use comparators, comparable interface!

Code

LinkedList<RowColElem<T>> rowColSeq;
 private void sortedLeftDiagSeq(int row, int col, T x){
      RowColElem<T> object = new RowColElem<T>(row, col, x);
      ListIterator<RowColElem<T>> iter = leftDiagSeq.listIterator();
      RowColElem<T> inListObject;
      boolean added = false;

      while(iter.hasNext()){
           inListObject = iter.next();
           if(object.getRow()-1 < inListObject.getRow() ||
              object.getRow()-1 == inListObject.getRow() &&
              object.getCol()-1 < inListObject.getCol()){
               if( iter.hasPrevious() ){
                   iter.add(object);
               }
           }
      }


  }

回答1:


Primary criterion is an elements "distance" from the main diagonal, negative distances indicating the lower triangle matrix.

if( object.getCol() - object.getRow() < inListObject.getCol() - inListObject.getRow()
    ||
    object.getCol() - object.getRow() == inListObject.getCol() - inListObject.getRow() &&
    object.getCol() < inListObject.getCol()){ ... }

I'm not sure about the last term. The data you've provided would also produce the expected result if row numbers are used to break the tie of equal distance from the main diagonal. Probably this doesn't matter since you want order from top-left to bottom-right within one diagonal.



来源:https://stackoverflow.com/questions/33062219/putting-elements-into-a-sorted-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!