我遇到麻烦了。它在结束之前循环一次。它接收具有各种名称和年龄的输入文件并对其进行排序。到目前为止它正在打印出来:
Stella is 11 years old.
Fred is 88 years old.
George is 22 years old.
Violet is 33 years old.
Rose is 77 years old.
Bob is 66 years old.
Lena is 55 years old.
Billy is 44 years old.
Nellie is 99 years old.
当我想要打印出来时:
Stella is 11 years old.
George is 22 years old.
Violet is 33 years old.
Billy is 44 years old.
Lena is 55 years old.
Bob is 66 years old.
Rose is 77 years old.
Fred is 88 years old.
Nellie is 99 years old.
当前代码:
public void bubbleSort()
{
PersonNode previous = head;
PersonNode current = head.getNext();
boolean swap = true;
int j = 0;
while(swap)
{
swap = false;
while(previous != null)
{
if(previous.getNext() != null && previous.getAge() > previous.getNext().getAge())
{
String tempName = previous.getName();
Integer tempAge = previous.getAge();
current = previous.getNext();
previous.setName(current.getName());
previous.setAge(current.getAge());
current.setName(tempName);
current.setAge(tempAge);
swap = true;
}
previous = previous.getNext();
}
}
感谢任何帮助。
答案 0 :(得分:1)
代码只会“冒泡”一个值,您需要从头开始重复该过程,直到不再发生交换。这是一个单行改变。
public void bubbleSort()
{
PersonNode previous = head;
PersonNode current = head.getNext();
boolean swap = true;
while(swap)
{
swap = false;
previous = head; /* restart */
while(previous != null)
{
if(previous.getNext() != null && previous.getAge() > previous.getNext().getAge())
{
String tempName = previous.getName();
Integer tempAge = previous.getAge();
current = previous.getNext();
previous.setName(current.getName());
previous.setAge(current.getAge());
current.setName(tempName);
current.setAge(tempAge);
swap = true;
}
previous = previous.getNext();
}
}