gpt4 book ai didi

c# - 单链表C#中的基数排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:17:17 27 4
gpt4 key购买 nike

我正在尝试在链表类中进行基数排序。我找到了数组的基数排序算法,并试图将其更改为与我的链表一起使用。但是,我有点挣扎。我试图更改的代码取自 http://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-10.php我用数组测试了代码并且它有效。有人知道如何在链表中进行基数排序吗?

//抽象类

abstract class DataList
{
protected int length;
public int Length { get { return length; } }
public abstract double Head();
public abstract double Next();
public abstract void Swap(int a, int b);
public void Print(int n)
{
Console.Write("{0} ", Head());
for (int i = 1; i < n; i++)
Console.Write("{0} ", Next());
Console.WriteLine();
}
}

//链表类

class LinkedList : DataList
{
class MyLinkedListNode
{
public MyLinkedListNode nextNode { get; set; }
public int data { get; set; }
public MyLinkedListNode(int data)
{
this.data = data;
}
public MyLinkedListNode()
{
this.data = 0;
}
}
MyLinkedListNode headNode;
MyLinkedListNode prevNode;
MyLinkedListNode currentNode;
public LinkedList(int n, int min, int max)
{
length = n;
Random rand = new Random();
headNode = new MyLinkedListNode(rand.Next(min, max));
currentNode = headNode;
for (int i = 1; i < length; i++)
{
prevNode = currentNode;
currentNode.nextNode = new MyLinkedListNode(rand.Next(min, max));
currentNode = currentNode.nextNode;
}
currentNode.nextNode = null;
}
public LinkedList()
{
headNode = new MyLinkedListNode();
currentNode = headNode;
}
public override double Head()
{
currentNode = headNode;
prevNode = null;
return currentNode.data;
}
public override double Next()
{
prevNode = currentNode;
currentNode = currentNode.nextNode;
return currentNode.data;
}
public override void Swap(int a, int b)
{
prevNode.data = a;
currentNode.data = b;
}

//我的基数排序

    public void radixSort()
{
int j = 0;
LinkedList tmp = new LinkedList();
for (int shift = 31; shift > -1; --shift)
{
//I try to go trough old list
MyLinkedListNode current = headNode;
while (current != null)
{
bool move = (current.data << shift) >= 0;
//I found this expression somewhere and I'm trying to use it to form a new Linked list (tmp)
if (shift == 0 ? !move : move)
;
else
{
if (tmp.headNode == null)
tmp.headNode = currentNode;
else
{
tmp.currentNode.nextNode = current;
//infinite loop happens on the commented line
//tmp.currentNode = tmp.currentNode.nextNode;
j++;
}
current = current.nextNode;
}
}
}
}

最佳答案

按照 C# 基数排序示例,您需要一个包含十个列表的数组。将原始列表中的节点移动到十个列表中,将具有最低有效数字 == '0' 的节点附加到 array_of_lists[0],'1' 附加到 array_of_list[1],依此类推。清空原始列表后,将列表数组连接回原始列表,并重复下一个最低有效位。重复该过程,直到处理完所有数字。

您可以使用更大的基数,例如基数 16,您可以在其中使用包含 16 个列表的数组。然后,您可以使用 shift 和 and 选择每个“数字”。

关于c# - 单链表C#中的基数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42782613/

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