[英]Radix Sort in File C#
这是大学的作业。 我必须以两种方式对汽车牌照(ABC 123)进行基数排序1)数组2)链表。 最有趣的是必须在文件中进行排序。 例如,从现在开始我们将只讨论数组。 我生成汽车号码并将它们放入数组中,然后使用二进制写入将所有生成的汽车注册牌写入文件。 之后,我将新生成的文件提供给 Radix Sort,他需要施展魔法。 我将向您展示我目前拥有的代码,但它实际上并不是一个“真正的”基数排序,因为我无法理解如何在文件中实现基数排序。 (我已经为普通数组和链表实现了基数排序,但是当它在一个文件中完成时,它是令人兴奋的)。 我只是想问一下你们中是否有人对我如何改进排序算法有任何提示或想法,因为它太慢了。 谢谢你。
程序.CS
public static void CountingSort(DataArray items, int exp)
{
UTF8Encoding encoder = new UTF8Encoding();
Byte[] forChange = new byte[16];
double first, second;
int i, j;
NumberPlate plate1;
NumberPlate plate2;
for (int z = 0; z < items.Length; z++)
{
i = 0;
j = 1;
while (j < items.Length)
{
BitConverter.GetBytes(items[i]).CopyTo(forChange, 0);
BitConverter.GetBytes(items[j]).CopyTo(forChange, 8);
string firstPlate = encoder.GetString(forChange, 1, 7);
string[] partsFirst = firstPlate.Split(' ');
plate1 = new NumberPlate(partsFirst[0], partsFirst[1]);
string secondPlate = encoder.GetString(forChange, 9, 7);
string[] partsSecond = secondPlate.Split(' ');
plate2 = new NumberPlate(partsSecond[0], partsSecond[1]);
first = plate1.GetPlateCode() / exp % 10;
second = plate2.GetPlateCode() / exp % 10;
if (first > second)
{
items.Swap(j, BitConverter.ToDouble(forChange, 0), BitConverter.ToDouble(forChange, 8));
}
i++;
j++;
}
}
}
public static void Radix_Sort(DataArray items)
{
for (int exp = 1; exp < Math.Pow(10, 9); exp *= 10)
{
CountingSort(items, exp);
}
}
public static void Test_File_Array_List(int seed)
{
int n = 5;
string filename;
filename = @"mydataarray.txt";
//filename = @"mydataarray.dat";
MyFileArray myfilearray = new MyFileArray(filename, n);
using (myfilearray.fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite))
{
Console.WriteLine("\n FILE ARRAY \n");
myfilearray.Print(n);
Radix_Sort(myfilearray);
myfilearray.Print(n);
}
}
数组
public override double this[int index]
{
get
{
Byte[] data = new Byte[8];
fs.Seek(8 * index, SeekOrigin.Begin);
fs.Read(data, 0, 8);
double result = BitConverter.ToDouble(data, 0);
return result;
}
}
public override void Swap(int j, double a, double b)
{
Byte[] data = new Byte[16];
BitConverter.GetBytes(b).CopyTo(data, 0);
BitConverter.GetBytes(a).CopyTo(data, 8);
fs.Seek(8 * (j - 1), SeekOrigin.Begin);
fs.Write(data, 0, 16);
}
如果赋值中提到了数组和链表,那么看起来文件只是用来将数据读入数组或链表中,然后进行排序,并将结果写入文件。
对于基于文件的基数排序,对于每个数字(从右到左),创建 10 个临时文件,读取数据并根据数字附加到文件“数字”,然后关闭 10 个临时文件,然后连接成一个用于下一个基数排序步骤的单个工作文件。 对于每个字母,将使用 26 个临时文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.