[英]insertion sort using linked list for Book objects
I'm trying to use insertion sort to sort linked list of Book alphabetically by title. 我正在尝试使用插入排序按书名的字母顺序对书的链接列表进行排序。
what I have done so far: 到目前为止我做了什么:
public void insertSorted(Book book){
if(books.getfirst()==null)
books.addFirst(book); //books is the LinkedList name
Node<Book> current =books.getfirst();
for(int i=0; i<books.getSize(); i++){
if(book.getTitle().compareToIgnoreCase(current.element.getTitle())<=0){
books.add(book, i);
}
}
the add method in Linkedlist: Linkedlist中的add方法:
public void add(Object x,int index){
if(index==0)addFirst(x);
else if(index>=getSize())addLast(x);
else{
Node current=first;
for(int i=0; i<index-1;i++)
current=current.next;
Node temp = new Node(x);
temp.next=current.next;
current.next=temp;
count++;
}
}
what exactly I'm doing wrong? 我到底在做什么错?
for(int i=0; i<books.getSize(); i++){
if(book.getTitle().compareToIgnoreCase(current.element.getTitle())<=0){
books.add(book, i);
}
With this statement (above), you are not incrementing the current Node
which is being compared. 使用此语句(上面),您不会增加正在比较的当前
Node
。 On each iteration of the for(;;)
loop, you are comparing the new Book
which is being added to this first element in the List
. 在
for(;;)
循环的每次迭代中,您都在比较要添加到List
第一个元素的新Book
。
The below code example should fix this: 下面的代码示例应解决此问题:
for(int i=0; i<books.getSize(); i++){
if(book.getTitle().compareToIgnoreCase(current.element.getTitle())<=0){
books.add(book, i);
break;
}
else {
current = current.next;
}
EDIT: Included required break statement, as per @Eden Lu answer 编辑:根据@Eden Lu答案包括必需的break语句
After you add the book to books, you need to break the loop 将书添加到书中后,需要打破循环
books.add(book,i); books.add(书,I); break;
打破;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.