我正在C#中使用通用列表,但我嘗試使用冒泡排序方法對節點進行排序時遇到問題。在C#中的通用列表Bubblesort#
namespace ConsoleApplication1
{
public class GenericList
{
private class Node
{
// Each node has a reference to the next node in the list.
public Node Next;
public int Data;
}
// The list is initially empty.
private Node head = null;
// Add a node at the beginning of the list with t as its data value.
public void AddNode(int t)
{
Node newNode = new Node();
newNode.Next = head;
newNode.Data = t;
head = newNode;
}
//list length
public int Size()
{
int listsize= 0;
Node current = head;
while (current != null)
{
listsize++;
current = current.Next;
}
return listsize;
}
//bubble sort
public void bubblesort()
{
int size = Size();
Node current = head;
for (int i = 1; i < size; i++)
{
for (int j = 0; j < size - 1; j++)
{
if (current.Data > current.Next.Data && current.Next!=null)
{
int temp = current.Data;
current.Data = current.Next.Data;
current.Next.Data = temp;
}
}
}
head = current;
}
}
}
當我向列表添加多於5個節點時,bubblesort方法停止工作(不正確地對列表進行排序)。 任何人都可以幫助嗎?
這個功課?如果沒有,只需使用List.Sort方法。 – tvanfosson 2011-03-18 16:47:33
確實看起來像一個大學班級的任務與這些意見...呃。 – 2011-03-18 16:49:22
將其稱爲通用列表會使您聽起來像是在使用'System.Collections.Generic.List',而不是您自己定製的'GenericList '。如果這不是家庭作業,只需要刪除'GenericList'並使用'List '(或'LinkedList '來更接近地匹配你所擁有的) –
Justin
2011-03-18 16:50:39