我必须快速排序链接列表上的递归....到目前为止我一直很好,但是我遇到了一个小问题,我无法弄清楚为什么它不能正常工作
这是对象Node:
public class Node
{
String name;
Node next;
}
这是程序的代码:
public class QuickSortRecusionLinkedList
{
public static void quickS(int start, int finish, Node head, Node tail)
{
int left = start;
int right = finish;
Node pivot = head;
for(int i = 0; i < ((left+right)/2); i++)
{
pivot = pivot.next;
}
Node temp = new Node();
Node leftN = head;
Node rightN = head;
while(right > left)
{
leftN = head;
for(int i = 0; i < left; i++)
{
leftN = leftN.next;
}
while ((leftN.name).compareToIgnoreCase((pivot.name))<0)
{
left = left + 1;
leftN = leftN.next;
}
rightN = head;
for(int i = 0; i < right; i++)
{
rightN = rightN.next;
}
while ((pivot.name).compareToIgnoreCase((rightN.name))<0)
{
right = right - 1;
rightN = head;
for(int i = 0; i < right; i++)
{
rightN = rightN.next;
}
}
if ( left <= right
)
{
temp.name = leftN.name;
leftN.name = rightN.name;
rightN.name = temp.name;
left = left +1;
leftN = leftN.next;
right = right -1;
rightN = head;
for(int i = 0; i < right; i++)
{
rightN = rightN.next;
}
int size = 1;
temp = head;
while (temp!=tail)
{
temp = temp.next;
size++;
}
temp = head;
while(temp != tail)
{
System.out.print(temp.name + ", ");
temp = temp.next;
}
System.out.println(tail.name + ".");
}
}
if(start < right)
quickS(start, right, head, tail);
if(left < finish)
quickS(left, finish, head, tail);
}
public static void main(String[] args)
{
Node head = new Node();
Node tail = new Node();
Node a = new Node();
Node b = new Node();
Node c = new Node();
head.name = "R";
tail.name = "D";
a.name = "Z";
b.name = "C";
c.name = "P";
head.next = a;
a.next = b;
b.next = c;
c.next = tail;
int size = 0;
Node temp = head;
while (temp!= tail)
{
temp = temp.next;
size++;
}
quickS(0,size,head,tail);
}
}
这是打印输出:
C, Z, R, P, D.
C, Z, R, P, D.
C, D, R, P, Z.
C, D, P, R, R.
C, D, P, R, R.
C, D, P, R, R.
最终结果应为C, D, P, R, Z
。但由于某种原因,该计划将Z
替换为另一个R
。代码有什么问题?
答案 0 :(得分:2)
可能的提示:当您使用它来交换名称时,请注意temp
变量指向的内容。
答案 1 :(得分:1)
尊重这似乎是一个傻瓜的差事。链接列表上的Quiksort将是但快速的任何内容。它的整个想法是使用数组。这里的目标是什么?