Kemal P.
Kemal P.

Reputation: 143

Putting elements into a sorted list

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);
               }
           }
      }


  }

Upvotes: 0

Views: 65

Answers (1)

laune
laune

Reputation: 31300

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.

Upvotes: 1

Related Questions