C# 数组中的反转数不正确

C# 数组中的反转数不正确,c#,arrays,sorting,mergesort,inversion,C#,Arrays,Sorting,Mergesort,Inversion,你能帮我找出我在C#上的代码中的一个错误吗?在数组中计算倒数?计数不正确。例如,在数组{3,8,6,1}中,它应该是4,但它是3。但是,它对数组{4,3,2,1}工作良好,并显示6。 程序读取的文本文件(1111.txt)中的每个字符串都包含一个数组元素。 多谢各位 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

你能帮我找出我在C#上的代码中的一个错误吗?在数组中计算倒数?计数不正确。例如,在数组{3,8,6,1}中,它应该是4,但它是3。但是,它对数组{4,3,2,1}工作良好,并显示6。 程序读取的文本文件(1111.txt)中的每个字符串都包含一个数组元素。 多谢各位

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace C
{
class Program
{
public static long k1 = 0;
static long Marge_sort(int[] A, int p, int r)
{
int q = p;
if (r <= p) return 0;
q = (p + r) / 2;
C.Program.k1 = Marge_sort(A, p, q);
C.Program.k1 += Marge_sort(A, q + 1, r);
C.Program.k1 += Marge(A, p, q, r);
return C.Program.k1; 
}
static long Marge(int[] A, int p, int q, int r)
{
long k1 = 0;

int n1 = q - p+1 ;
int[] L = new int[n1+1];
int n2 = r - q;
int i;
int[] R = new int[n2+1];
for(i=0;i<n1;i++)
{
L[i] = 0;
L[i] = A[p + i ];
}
L[n1] = int.MaxValue;
for (i = 0; i < n2; i++)
{
R[i] = 0;
R[i] = A[q + i+1];
}
R[n2] = int.MaxValue;
int j = 0; i = 0;
for(int k=p;k<=r;k++)
{
if (L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
k1 = q - i+1 ;
}

}
return k1;

}
static void Main(string[] args)
{
long k1 = 0;
int leght = 0, el = 0;
int[] Ch = new int[leght];
StreamReader s = File.OpenText(@"D:\1111.txt");//IntegerArray
string read = null;
while ((read = s.ReadLine()) != null)
{
//Console.WriteLine(read);
leght++;
Array.Resize(ref Ch, leght);
Ch[el] = Convert.ToInt32(read);
el++;
}
s.Close();
k1=Marge_sort(Ch, 0, leght-1 );

Console.WriteLine("\n"+k1.ToString());
Console.ReadLine();

}

}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.IO;
命名空间C
{
班级计划
{
公共静态长k1=0;
静态长边排序(int[]A,int-p,int-r)
{
int q=p;

如果(r对于数组{3,6,8,1}),正确答案是3:


{3,6,8,1}->{3,6,1,8}->{3,1,6,8}->{1,3,6,8}

靠近
Marge

k1 = q - i+1 ;
应该是

k1 += n1 - i;
首先,您要记录必须在前面移动
R
元素的
L
元素总数。因此,运算符应该是
+=
而不是
=

其次,
q
测量原始数组
a
中的一个位置。您正在计算小数组
L
中的许多元素,因此您应该从
n1
中减去索引,即该数组的大小(不包括保护值)。如果
A
很大,您将开始看到疯狂的结果:当您合并只有几个元素的小子数组,但非常接近
A
的顶部时,您将看到
q
的巨大值,这与
L
的大小无关


当您确定代码正常工作后,您应该访问codereview.stackexchange.com。它们只对正常工作的代码有帮助,但它们会为您提供大量关于如何以更干净、更可读的方式编写代码的指针。您的代码充满了小错误,如不必要的命名空间、未使用的初始化等(但我认为在担心这些问题之前让它正常工作是正确的方法。)

你能改进格式吗?例如,在数组{3,6,8,1}中,它应该是4,但它是3。我认为它应该是3。(3,1),(6,1),(8,1)对不起,我是说{3,8,6,1}代表{1,2,3,4}它显示了2个倒数,当它应该是0时,它为数组{3,8,6,1}返回4。请在发布问题之前尝试检查是否有这样的错误和打字错误。在有人花时间尝试检查结果是错误的内容后,他们可能不愿意再花时间帮助您。非常感谢!)终于成功了!你救了我。再次感谢你