我的bubblesort有问题。它在结束前循环一次。它接收一个具有不同名称和年龄的输入文件并对其进行排序。到目前为止,它正在打印:
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();
}
}
感谢您的帮助。
代码只"冒泡"一个值,您需要从一开始就重复这个过程,直到不再发生交换为止。这是一个单行变更。
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();
}
}