最近得到了一个有效的冒泡排序算法,并决定尝试合并排序算法,我正在尝试从头开始编写它作为个人挑战,我觉得我的逻辑似乎在它的根本上是有缺陷的,但是,不知道还可以向哪里寻求建议,我欢迎任何输入。我觉得C#不喜欢我声明的子数组,它们似乎也是一个不合适的解决方案
public static void MergeSort(int[] A) // WIP
{
if (A.Length % 2 == 0 ) //Checks if input array is even
{
int[] B; //Declares sub array
int[] C; //Declares sub array
for (int x = 0; x < A.Length ; x++) //Performs an action for every item item in the array
{
if (x < A.Length / 2) //selects the first half of the input array and assigns it to sub-Array B
{
B[x] = A[x];
}
if(x > A.Length / 2) //Selects the second half of the input array and assigns it to sub-Array C
{
C[x] = A[x];
}
}
}发布于 2017-06-08 02:59:28
您声明了对数组的引用,但从未初始化它们。B和C将为空,如果您尝试对它们执行任何操作,都会得到一个异常。
// Declares *reference* to sub array, and creates it as well.
int[] B = new int[A.Length];
// Declares *reference* to sub array, and creates it as well.
int[] C = new int[A.Length];您可以使用List<int>而不是数组。
问题是,您将只使用B的前半部分和C的后半部分。这是你想要的吗?如果您希望B只是A的前半部分,而C只是A的后半部分,请执行以下操作。您可以使用与数组几乎相同的方式使用List<int>,但您可以Add()到它,并且它有一个Count属性而不是Length属性:
var B = new List<int>();
var C = new List<int>();
for (int x = 0; x < A.Length ; x++) //Performs an action for every item item in the array
{
if (x < A.Length / 2) //selects the first half of the input array and assigns it to sub-Array B
{
B.Add(A[x]);
}
if(x > A.Length / 2) //Selects the second half of the input array and assigns it to sub-Array C
{
C.Add(A[x]);
}
}另一件事:为了清楚起见,我在这里的第二个if之前放了一个else,而不是运行时效率。
但是如果x等于A.Length / 2会发生什么呢?如果这种情况是在您的问题中没有包含的代码中处理的,那么请不要担心。
if (x < A.Length / 2) //selects the first half of the input array and assigns it to sub-Array B
{
B.Add(A[x]);
}
else if(x > A.Length / 2) //Selects the second half of the input array and assigns it to sub-Array C
{
C.Add(A[x]);
}但是,您可以按如下方式简化该代码:
if (A.Length % 2 == 0)
{
// Take the first half and make an array out of that sequence
var B = A.Take(A.Length / 2).ToArray();
// Skip the first half and make an array out of the remaining sequence
var C = A.Skip(A.Length / 2).ToArray();
}但是,如果您打算演示基本编程基础知识,而不是C#琐事,那么循环方法是最好的。
发布于 2017-06-08 03:28:58
因为您正在尝试使用未赋值的变量(数组B和C),所以会收到错误。如果您需要了解数组是如何工作的,请转到here。如果您初始化int[B] = new int[A.Length / 2];,那么您的代码将不会出现任何错误。
你的代码应该是这样的,只是为了工作,我没有重构任何东西,只是做了最小的事情让它工作:
public static void MergeSort(int[] A) // WIP
{
if (A.Length % 2 == 0) //Checks if input array is even
{
int[] B = new int[A.Length / 2]; //Declares sub array
int[] C = new int[A.Length / 2]; //Declares sub array
for (int x = 0; x < A.Length; x++) //Performs an action for every item item in the array
{
if (x < A.Length / 2) //selects the first half of the input array and assigns it to sub-Array B
{
B[x] = A[x];
}
if (x > A.Length / 2) //Selects the second half of the input array and assigns it to sub-Array C
{
C[x] = A[x];
}
}
}
}发布于 2017-06-09 22:45:35
现在我的主要问题是如何知道我需要创建多少个数组,以便将所有数组分解为大小为1的数组(当原始输入未知时),我觉得这不是一个很好的实现
https://stackoverflow.com/questions/44420725
复制相似问题