我正在用Java實現我自己的鏈表。節點類只有一個名爲「name」的字符串字段和一個名爲「link」的節點。現在我有一個測試驅動程序類,它只能順序插入幾個名字。現在,我正在嘗試編寫一個排序方法來按字母順序排列節點,但是我遇到了一些麻煩。我從別人的帖子中發現了這個冒泡的僞代碼,並試圖實現它,但是它沒有完全分類條目。我不太清楚爲什麼。任何建議表示讚賞!用Java手動排序鏈表(詞法)
private void sort()
{
//Enter loop only if there are elements in list
boolean swapped = (head != null);
// Only continue loop if a swap is made
while (swapped)
{
swapped = false;
// Maintain pointers
Node curr = head;
Node next = curr.link;
Node prev = null;
// Cannot swap last element with its next
while (next != null)
{
// swap if items in wrong order
if (curr.name.compareTo(next.name) < 0)
{
// notify loop to do one more pass
swapped = true;
// swap elements (swapping head in special case
if (curr == head)
{
head = next;
Node temp = next.link;
next.link = curr;
curr.link = temp;
curr = head;
}
else
{
prev.link = curr.link;
curr.link = next.link;
next.link = curr;
curr = next;
}
}
// move to next element
prev = curr;
curr = curr.link;
next = curr.link;
}
}
}
對於它的價值,我認爲比較中的「<」會讓你的排序進入DESCENDING順序。 – 2009-12-06 09:42:41
你能給一個「不完全排序條目」的例子嗎? - 你的bubblesort代碼看起來不錯 – 2009-12-06 10:26:39