gpt4 book ai didi

java - 双链表的冒泡排序

转载 作者:行者123 更新时间:2023-12-01 14:49:09 25 4
gpt4 key购买 nike

花了几个小时试图让冒泡排序的实现在双链表上工作。我的代码似乎适用于一次传递,但随后过早完成而没有完成排序。任何指导将不胜感激。

public void bubbleSort()
{
Node cur = head.getNext();
boolean done = false;

while (!done)
{
done = true;
while(cur != tail)
{
if (cur.getNext().getCount()>cur.getCount())
{
swap(cur.getNext(),cur);
done=false;
}
cur = cur.getNext();
}
}
}

我正在使用的交换方法似乎会破坏节点的位置,直到它成为两个节点之间的循环。

private void swap(Node n1, Node n2)
{
Node b1, b2, a1, a2;
System.out.println("Swapping n1: " + n1 + " with n2: " + n2);
b1 = n2.getPrev();
if (b1 == n1) // handle adjacent nodes
b1 = n2;
a1 = n2.getNext();

b2 = n1.getPrev();
if (b2 == n2) // handle adjacent nodes
b2 = n1;
a2 = n1.getNext();

// swap

n1.setPrev(b1);
n1.setNext(a1);

n2.setPrev(b2);
n2.setNext(a2);

b1.setNext(n1);
a1.setPrev(n1);

b2.setNext(n2);
a2.setPrev(n2);
}

谢谢

最佳答案

我在您的代码中看到的问题:

  • 您应该从 head 开始,而不是从 head.getNext() 开始。
  • 您应该在每次 while(!done) 迭代时重新启动 Node cur

通过这些更改,您的代码应该是

public void bubbleSort() {
boolean done = false;
while (!done) {
Node cur = head;
done = true;
while(cur != tail) {
if (cur.getNext().getCount()>cur.getCount()) {
swap(cur.getNext(),cur);
done=false;
}
cur = cur.getNext();
}
}
}

此代码假定您的 swap 方法可以正常工作。使用 int count 作为 Node 类中的数据进行测试,并在列表上分配 10000 个 int 值。

<小时/>

编辑:根据您的问题编辑,我制作了我的 Node 类和 swap 函数,如下所示:

private static class Node {
int count;
Node next;
//getters and setters...
}

//this function just swaps data, no need to swap the nodes prev and next
//(note that yours is an algorithm design issue)
private void swap(Node node1, Node node2) {
int aux = node1.getCount();
node1.setCount(node2.getCount());
node2.setCount(aux);
}

无需执行您在 swap 实现中完成的所有样板代码。

关于java - 双链表的冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com