作为提高我的编程技能计划的一部分,我决定尝试按字典顺序对大量字符串进行排序(稍后我计划使用线程来这样做)。我研究了不同的排序算法,并尝试根据我的理解实现一个合并排序。现在我打算对一些简单的字符串进行排序。
我正在输入以下要在以下方法中排序的字符串:
string[] stringsArray = new string[] { "cixymn", "adfxij", "adxhxy", "abcdef", "iejfyq", "uqbzxo", "aaaaaa" };
string[] stringSorted = MergeSort(stringsArray);
// For display purposes
foreach (string s in stringSorted)
{
Console.WriteLine("Item at index " + Array.IndexOf(stringSorted, s) + " is " + s);
}
我得到的结果如下:
Item at index 0 is aaaaaa
Item at index 1 is abcdef
Item at index 2 is adfxij
Item at index 3 is uqbzxo
Item at index 4 is
Item at index 4 is
Item at index 4 is
由于要实现归并排序,必须先将数组一分为二,我很容易理解,在这种情况下,左边部分排序成功,右边部分被忽略。我的印象是这种情况正在发生,因为我在每次递归中比较数组左侧的每个字符串的字符(因此可能忽略右侧)。所以我想我真的明白问题可能出在哪里。但是,我不太清楚该怎么做。任何帮助将不胜感激。
下面是 MergeSort 方法的代码。
private static string[] MergeSort(string[] stringsArray)
{
if (stringsArray.Length == 1)
{
return stringsArray;
}
int middle = stringsArray.Length / 2;
string[] left = new string[middle];
string[] right = new string[stringsArray.Length - middle];
for (int i = 0; i < middle; i++)
{
left[i] = stringsArray[i];
}
for (int i = 0; i < stringsArray.Length - middle; i++)
{
right[i] = stringsArray[i + middle];
}
left = MergeSort(left);
right = MergeSort(right);
int leftPointer = 0;
int rightPointer = 0;
string[] sorted = new string[stringsArray.Length];
for (int k = 0; k < stringsArray.Length; k++)
{
if (k == left.Length)
{
break;
}
for (int i = 0; i < left[leftPointer].Count(); i++)
{
var leftChar = left[leftPointer][i];
if (i == right[rightPointer].Count())
{
continue;
}
var rightChar = right[rightPointer][i];
if ((rightPointer == right.Length || leftPointer < left.Length) && leftChar < rightChar)
{
sorted[k] = left[leftPointer];
sorted[k + 1] = right[rightPointer];
leftPointer++;
break;
}
if ((leftPointer == left.Length || rightPointer < right.Length) && (rightChar < leftChar))
{
sorted[k] = right[rightPointer];
sorted[k + 1] = left[leftPointer];
rightPointer++;
break;
}
}
}
问题 #2:您会如何建议优化代码以便能够使用线程?