[英]BubbleSort on Custom LinkedList
我正在嘗試對“數據”進行排序。 假定數據按數字排序。 我正在嘗試實現BubbleSort(),但無法處理相同的問題。
public void bubbleSort() {
if (isEmpty())
{
System.out.println("The Empty List Is Already Sorted");
}
else if (first.next == null) {
System.out.println("One Element List Is Already Sorted");
}
else {
Node current = first;
boolean swapDone = true;
while (swapDone) {
swapDone = false;
while (current != null) {
if (current.next != null && current.value.getScore() > current.next.value.getScore()) {
Data temp = current.value;
current.value.setScore(current.next.value.getScore());
current.value.setName(current.next.value.getName());
current.next.value.setScore(temp.getScore());
current.next.value.setName(temp.getName());
}
current = current.next;
}
current = first;
}
}
查看此代碼是否有效
public void bubbleSort() {
if (isEmpty())
{
System.out.println("The Empty List Is Already Sorted");
}
else if (first.next == null) {
System.out.println("One Element List Is Already Sorted");
}
else {
Node current = first;
boolean swapDone = true;
while (swapDone) {
swapDone = false;
while (current != null) {
if (current.next != null && current.value.getScore() > current.next.value.getScore()) {
Data temp = current.value;
current.value.setScore(current.next.value.getScore());
current.value.setName(current.next.value.getName());
current.next.value.setScore(temp.getScore());
current.next.value.setName(temp.getName());
swapDone=true;
}
current = current.next;
}
current = first;
}
}
在第一個循環之后,swapDone將始終為false。 您只會經歷一次內循環
這是工作代碼。
public void bubbleSort() {
if (isEmpty())
{
System.out.println("The Empty List Is Already Sorted");
}
else if (first.next == null) {
System.out.println("One Element List Is Already Sorted");
}
else {
Node current = first;
boolean swapDone = true;
while (swapDone) {
swapDone = false;
while (current != null) {
if (current.next != null && current.value.getScore() >
current.next.value.getScore()) {
Data temp = current.value;
current.value = current.next.value;
current.next.value = temp;
swapDone = true;
}
current = current.next;
}
current = first;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.