我正在尝试使用冒泡排序对项目列表进行排序。我知道这不是最有效的排序方法;但是,在继续做更好的事情之前,我需要这种方法起作用。我当前的代码对列表进行了部分排序,但我看不出我做错了什么。
public class ListComponents
{
public int Priority;
public string Name;
public ListComponents Next;
}
public void bubblesort()
{
ListComponents Current = Head;
int temp = 0;
bool swapped = true;
while (swapped)
{
Print(); // Debug Function to print each swap
Current = Head.Next; // RESET CURRENT TO HEAD + 1 ON EACH ITERATION?
swapped = false;
for (int sort = 0; sort < (size - 1); sort++) //Size defined as # of items in list
{
if (Current != null &&
Current.Next != null &&
Current.Priority> Current.Next.Priority)
{
temp = Current.Priority;
Current.Priority= Current.Next.Priority;
Current.Next.Priority= temp;
Current = Head; // POTENTIAL ISSUE?
swapped = true;
}
}
}
}
我的调试打印功能显示以下内容,显示这些值几乎是按顺序排列的:
List: 4 2 1 3 (Inital List Order)
List: 1 4 2 3 (First Swap)
List: 1 2 4 3 (Second Swap)
问题似乎与设置“当前”值有关,尽管我看不出这在哪里不起作用。