I have a node class that I made which has an int for row, column, and data. I am trying to make a sparse matrix. I want to sort them as I add them to be more efficient. I first need to sort by row, then by column if the row is the same. I have experimented with a few different ways but none of them are working. I am using the Java linkedList class as well as the Iterator. For example, if add elements (1,1,3), (2,2,4), and (1,3,5), when I print it out, it should be (1,1,3), (1,3,5), and (2,2,4).
This is my code so far:
public void addElement(int row, int col, int data) {
if(matrix.size() == 0){
Node new_node = new Node(row, col, data);
matrix.add(new_node);
System.out.print("test \n");
}
Iterator<Node> iterator = matrix.iterator();
Node temp = new Node();
temp = iterator.next();
int i = -1; // counter
int size = matrix.size();
int node_row = temp.getRow();
int node_col = temp.getColumn();
System.out.print("iterator test \n");
while(iterator.hasNext() || size == 1){
System.out.print("test 5");
while(row>node_row){
i++;
node_row++;
}
while(row == node_row && col>node_col){
i++;
node_col++;
}
break;
}
if(i<=0){
Node new_node = new Node(row, col, data);
matrix.add(0, new_node);
}
else{
Node new_node = new Node(row, col, data);
matrix.add(i, new_node);
}
}
Thank you for the help!!